且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Moq调用类中的另一种方法

更新时间:2023-11-23 11:57:46

您遇到了这个问题,因为您在嘲笑要测试的内容.这没有道理.

You are having this problem because you are mocking what you are testing. This doesn't make sense.

您是正确的,Moq将用自己的方法替换您的方法的实现.原因是您应该使用Moq来模拟正在测试的调用中的内容,而不是正在测试的类.

You are correct that Moq will replace the implementation of your method with its own. The reason is you are supposed to use Moq to mock things the class you are testing calls, not the class you are testing itself.

如果您的代码是按以下方式设计的,则此测试将是适当的:

This test would be appropriate if your code were designed thusly:

public class ClassA
{
    BusinessLogicClass bl;
    public ClassA(BusinessLogicClass bl)
    {
         this.bl = bl;
    }

    public void Save()
    {
        bl.ShouldBeCalled();
    }
}

public class BusinessLogicClass
{
    public virtual void ShouldBeCalled()
    {
        //This should get executed
    }
}

这是该方法的正确测试:

And here is the correct test of that method now:

[TestFixture]
public class ClassA_Test
{
    [Test]
    public void Save_ShouldCallShouldBeCalled()
    {
        //Arrange
        var mockBLClass = new Mock<BusinessLogicClass>();
        mockBLClass.Setup(x => x.ShouldBeCalled()).Verifyable();

        //Act    
        ClassA classA = new ClassA(mockBLClass.Object);
        classA.Save();

        //Assert
        mockBLClass.VerifyAll();
    }
}

这里的主要课程是模拟/存根测试需要运行的内容,而不是测试本身.

The key lesson here is that you mock/stub what your test needs to run, not what you are testing itself.

希望这会有所帮助, 安德森

Hope this helps, Anderson