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

How to mock an interface with multiple implementation?

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

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 class 中实现的 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
         
    }
}

您似乎对模拟对象的用途感到困惑。您不要 模拟您正在测试的class。模拟旨在替换您测试的 classes 的依赖项(如示例中的 p 构造函数参数)。要测试 class 实例化要测试的实际 class,所以:

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

         //Act
         foo.DoSomething();             

         //Assert
         
    }
}