[英]How to mock an object that extends a class and implements an interface?
I have this class: 我有这门课:
public class BaseFoo
{
public bool BoolProp { get; set; }
}
public interface IFoo {
void Method();
}
public class FooClass : BaseFoo, IFoo
{
public void Method()
{
// DoSomething
}
}
public class MyClass
{
IFoo foo; //
public MyClass(IFoo foo)
{
this.foo = foo;
}
public void DoSomething()
{
if (((FooClass)foo).BoolProp)
{
// yeah
}
else
{
//bad
}
}
}
My scenario is: 我的情况是:
void main()
{
MyClass obj = new MyClass(new FooClass());
obj.DoSomething();
}
I'd like to create a mock object for the IFoo interface that allows me to mock the BaseFoo class too because I need to always avoid running the "else" branch of the "if (((FooClass)foo).BoolProp)" in the MyClass.DoSomething() method. 我想为IFoo接口创建一个模拟对象,它允许我模拟BaseFoo类,因为我需要总是避免运行“if(((FooClass)foo).BoolProp)”的“else”分支。 MyClass.DoSomething()方法。
So, how can I create a mock object that allows me to mock the behaviour of BaseFoo.BoolProp used in MyClass (that will take a mock object of IFoo)? 那么,我怎样才能创建一个模拟对象,允许我模拟MyClass中使用的BaseFoo.BoolProp的行为(这将采用IFoo的模拟对象)?
I did that without any result because the "BoolProp" is not virtual and I can't change it as it is part of a .NET Framework class: 我没有任何结果,因为“BoolProp”不是虚拟的,我无法更改它,因为它是.NET Framework类的一部分:
var cMock = new Mock<BaseFoo>();
var iMock = cMock.As<IFoo>();
cMock.Setup(c => c.BaseProp).Returns(true);
MyClass myClass = new MyClass(iMock.Object);
What your design is really saying is that your class MyClass
does not have a dependency on IFoo
, it has a dependency on a class instance derived from BaseFoo
and implementing IFoo
. 你的设计真正说的是你的类
MyClass
没有依赖于IFoo
,它依赖于从BaseFoo
派生的类实例并实现IFoo
。 In this case it is probably best that you introduce a unifying interface which you can then use as a dependency and mock: 在这种情况下,最好引入一个统一的接口,然后可以将其用作依赖项和mock:
interface IFooBar
{
bool BoolProp { get; set; }
void Method();
}
How about declaring an abstract class (BaseFooFoo?) that derives from BaseFoo and implements IFoo. 如何声明一个派生自BaseFoo并实现IFoo的抽象类(BaseFooFoo?)。 Then you could show BaseFooFoo to moq.
然后你可以向moq显示BaseFooFoo。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.