如何模拟被测类中的方法?

问题描述

我使用的是 Moq v4.13 和 C#。 我正在尝试在 MethodA 的接口上测试方法 MyClass : IMyInterfaceMethodA 调用了另一个接口 (IAnother) 的方法,我已经设置了这些方法。这些似乎设置得很好。

MethodA 还在 MethodB调用 IMyInterface(也在 MethodC 上)和 IMyInterface(公开,但不在 MyClass 上)。

我已经设置了 MethodB,但在测试时,似乎调用MethodB 的实际代码

至于 MethodC,我不知道如何设置。

public interface MyInterface 
{
    int MethodA();
    int MethodB();
}
public class MyClass : MyInterface 
{
    public MyClass(IAnother b) {...}
    
    public int MethodB(){...}
    public int MethodC(){...}

    public int MethodA()
    {
        ...
        var x = b.MethodX();
        ...
        var a = MethodB();
        ...
        var b = MethodC()

        return a + b + x;
    }
}
public MyInterfaceHarness
{
   Mock<IAnother> _anotherMock;

   public MyInterfaceHarness() 
   {
       _anotherMock = new Mock<IAnother>();
       Mocker = new AutoMocker();
   }

   public AutoMocker Mocker {get;}
   
   public MyClass MethodAHarness()
   {
       Mocker.Use(_anotherMock)  // Mocker is Automocker
       _anotherMock.Setup(m => m.MethodX()).Returns(5); // this seems to be setup fine

      //here I want to setup invocations to MethodB and MethodC
      ....

      Mocker.CreateInstance<MyClass>();
   }
}
[TestFixture]
public MyInterfaceTest 
{
    private  MyInterfaceHarness _harness;
    private AutoMocker _mocker;

    [SetUp]
    public void SetUp()
    {
       _harness = new MyInterfaceHarness();
       _mocker = _harness.Mocker();
    }

    [Test]
    public void Should_Test_MethodA()
    {
        var mi = _harness.MethodAHarness();

        // use _mocker to setup other invocations that need verify            
        ...

        var i = mi.MethodA();
       
       //asserts
       ...
        
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...