验证一个方法是否在单元测试中的另一个方法中被调用

pri*_*iya 2 c# unit-testing moq mvvm

我正在对视图模型进行单元测试,并使用带有起订量的 mbunit 来模拟类的私有方法,但我的要求是在测试的断言部分中验证是否调用了另一个方法(这是一个对话框)。单元测试下的方法。

Fre*_*jck 5

您可以使用以下代码轻松检查使用 Moq 调用的方法:

[TestFixture]
public class UnitTest1
{
    [Test]
    public void TestMethod1()
    {
        // Create a mock of your interface and make the methods verifiable.
        var mock = new Mock<ISomeDependency>();
        mock.Setup(m => m.DoSomething())
            .Verifiable();

        // Setup your class which you expect to be calling the verifiable method
        var classToTest = new SomeClass(mock.Object);
        classToTest.DoWork();

        // Verify the method is called
        mock.Verify(m => m.DoSomething());
    }
}



public class SomeClass
{
    private readonly ISomeDependency _someDependency;

    public SomeClass(ISomeDependency someDependency)
    {
        _someDependency = someDependency;
    }

    public void DoWork()
    {
        _someDependency.DoSomething();
    }
}

public interface ISomeDependency
{
    void DoSomething();
}

public class SomeDependency : ISomeDependency
{
    public void DoSomething()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,您要寻找的只是单元测试的排列部分中的可验证,以及断言部分中的验证。