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

标签 c# unit-testing mvvm moq

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

最佳答案

您可以使用以下代码轻松检查使用 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()
    {

    }
}

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

关于c# - 验证一个方法是否在单元测试中的另一个方法中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22376497/

相关文章:

ios - 为单元测试禁用一些代码行

c# - 如何使用将验证考虑在内的构建器自动创建测试数据

c# - 如果值为字符串类型则按片段搜索,但如果值为 int 则按整个搜索

c# - 如何在C#中填写DTO

c# - Azure Linux ASP 上运行的 .net core 与 Azure SQL 数据库之间的连接池问题

c# - 将字符串转换为运算符?

c# - 使用 JSON.NET 序列化时如何将属性从接口(interface)继承到对象

amazon-web-services - Golang : mocking AWS services which have same method name

data-binding - WinRT ViewModel DataBind 到异步方法

wpf - 将图表 LegendItem 复选框绑定(bind)到 WPF 中的系列可见性