MOQ - 如何模拟需要转换为另一个接口的接口? [英] MOQ - how to mock an interface that needs to be cast to another interface?

查看:159
本文介绍了MOQ - 如何模拟需要转换为另一个接口的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是为I1构建一个moq - 这很好......但是在我测试的方法过程中使用这个模拟我需要将它转换为I2才能访问一些属性不在I1上

what I want to do is construct a moq for I1 - which is fine ... however in the course of the method that I am testing that uses this mock I need to cast it to I2 in order to access some properties that are not on I1

Interface I1 
{ int AProperty{get;set;}}

Interface I2
{int AnotherProperty{get;set;}}

然后我有一些对象

Class O1 : I1 {}

Class O2 : O1 , I2 {}

问题是,当我有一个I2实现对象的实例时,我可以将它转换为I1以便访问方法通过该接口实现。在代码中,这不是问题,并且每个标记都按预期工作。

the problem is that when i have an instance of a I2 implementing object I can cast it to I1 in order to access the methods that are implmented through that interface. In code this is not a problem and everythign works as expected.

在该类上编写单元测试时唯一的问题是。

The only problem comes when writing a unit test on that class.

接口还公开了一个名为GetNewInstance的方法,该方法返回一个初始化的实现对象的实例,该实例对象被转换为IGetNewInstance接口...我通常可以模拟这个并使其自行返回(所以我继续使用模拟对象)。

The interfaces also expose a method called GetNewInstance which returns an initialised instance of the the implementing object cast into the IGetNewInstance interface ... i can usually mock this fine and make it return itself (and so I keep working with the mock object).

但是当你尝试将这个类型为I2的返回对象转换为I1时,空引用结果 - 这是有意义的,因为实现I2的模拟对象不继承任何继承I1的东西。

however when you try to cast this returned object of type I2 into I1 a null reference results - this makes sense as the mock object that implements I2 does not inherit from anything that inherits I1.

问题是我如何强制模拟对象同时从I1和I2继承?

the question is how can i force the mock object to inherit from both I1 ansd I2 at the same time?

推荐答案

我理解你的方式,你想创建一个实现两个接口的模拟器。使用Moq,就是这么简单:

The way I understand you, you want to create a mock that implements two interfaces. With Moq, that is as simple as this:

var mock = new Mock<IFoo>(); // Creates a mock from IFoo
mock.As<IBar>(); // Adds IBar to the mock
mock.As<IBar>().Setup(m => m.BarMethod()).Returns(new object()); // For setups.

现在,您可以设置期望并使用您的模拟,因为您通常会使用实现两者的对象 IFoo IBar

Now, you can set up expectations and use your mock as you would normally use the object implementing both IFoo and IBar.

为您的 GetNewInstance 方法,你可以设置一个返回模拟本身的期望。

For your GetNewInstance method, you can just set up an expectation that returns the mock itself.

这篇关于MOQ - 如何模拟需要转换为另一个接口的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆