如何模拟具有多个实现的接口



我有一个由两个类实现的接口。

public IMyInterface
{
void DoSomething();
}

public abstract class MyBaseClass
{
internal readonly SomeParameter p;
public MyBaseClass (SomeParameter p)
{
this.p = p;
}
}

public class Foo : MyBaseClass, IMyInterface
{
public Foo (SomeParameter p) : base(SomeParameter p)
{
}
}

public class Bar : MyBaseClass, IMyInterface
{
public Bar (SomeParameter p) : base(SomeParameter p)
{
}
}

现在我应该如何使用Moq测试Foo类中实现的DoSomething()方法?

@Nkosi我想做一些类似以下的事情。

public class FooTest
{
[Fact]
public void DoSomethingTest()
{
//Arrange
//Here I'm facing problem to get a mock for Foo class. 
//Mock of IMyInterface must be Foo here.
var foo = new Mock<IMyInterface>();
//Act
//Another problem: Here DoSomething is not getting called.
foo.DoSomething();             
//Assert

}
}

您似乎对mock对象的作用感到困惑。您不模拟正在测试的类。Mock旨在替换测试类的依赖项(如示例中的p构造函数参数(。为了测试类,您实例化了要测试的实际类,因此:

public class FooTest
{
[Fact]
public void DoSomethingTest()
{
//Arrange
var p = new Mock<SomeParameter>();
var foo = new Foo(p.Object);
//Act
foo.DoSomething();             
//Assert

}
}

最新更新