使用Moq的,以确定是否一个方法被称为被称为、方法、Moq

2023-09-02 10:30:52 作者:終

这是我的理解,我可以测试会出现一个方法调用,如果我叫了更高水平的方法,即:

It is my understanding that I can test that a method call will occur if I call a higher level method, i.e.:

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

    internal abstract void SomeOtherMethod();
}

我想测试一下,如果我称之为的someMethod()然后,我想到的是 SomeOtherMethod()将被称为。

I want to test that if I call SomeMethod() then I expect that SomeOtherMethod() will be called.

我是正确的思维这种测试可在一个模拟框架?

Am I right in thinking this sort of test is available in a mocking framework?

推荐答案

您可以看到,如果在一些方法你嘲笑被称为使用验证,如:

You can see if a method in something you have mocked has been called by using Verify, e.g.:

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();
}

如果该行留下评论说,当你调用验证它会抛出一个MockException。如果没有被注释它会通过。

If the line is left commented it will throw a MockException when you call Verify. If it is uncommented it will pass.