使用Moq确定是否调用方法

Owe*_*wen 153 .net c# unit-testing moq mocking

我的理解是,如果我调用更高级别的方法,我可以测试是否会发生方法调用,即:

public abstract class SomeClass()
{    
    public void SomeMehod()
    {
        SomeOtherMethod();
    }

    internal abstract void SomeOtherMethod();
}
Run Code Online (Sandbox Code Playgroud)

我想测试一下,如果我打电话,SomeMethod()那么我希望它SomeOtherMethod()会被调用.

我认为这种测试可以在模拟框架中使用吗?

Pau*_*aul 181

您可以通过使用Verify查看是否已使用模拟调用某个方法中的方法,例如:

static void Main(string[] args)
{
        Mock<ITest> mock = new Mock<ITest>();

        ClassBeingTested testedClass = new ClassBeingTested();
        testedClass.WorkMethod(mock.Object);

        mock.Verify(m => m.MethodToCheckIfCalled());
}

class ClassBeingTested
{
    public void WorkMethod(ITest test)
    {
        //test.MethodToCheckIfCalled();
    }
}

public interface ITest
{
    void MethodToCheckIfCalled();
}
Run Code Online (Sandbox Code Playgroud)

如果对该行进行了注释,则在调用Verify时将抛出MockException.如果它被取消注释,它将通过.

  • -1:.Expect(...).Verifiable()在此代码中是多余的.使用AAA验证您的正确性..Verifiable用于.Verify()i,.e.没有arg版本.见http://stackoverflow.com/questions/980554/what-is-the-purpose-of-verifiable-in-moq/1728496#1728496 (25认同)
  • 这是正确的答案.但是,你必须明白一些事情.您无法模拟非抽象或虚拟的方法/属性(显然,可以模拟所有接口方法和属性). (7认同)

小智 6

不,模拟测试假设您正在使用某些可测试的设计模式,其中之一是注入.在您的情况下,您将进行测试,SomeClass.SomeMethod 并且SomeOtherMethod必须在需要接口的另一个实体中实现.

你的Someclass构造函数看起来像New(ISomeOtherClass).然后你会模拟ISomeOtherClass并设置对它的期望,SomeOtherMethod并验证期望.