c# - NSubstitute 模拟一个没有参数的 void 方法

标签 c# unit-testing testing mocking nsubstitute

我是 NSubstitute 的新手,我正在尝试使用 2 个 out 参数模拟一个 void 方法,我很确定我做错了。

我有一个 CustomerDataAccess 类,它的方法具有以下签名:

void GetCustomerWithAddresses(int customerId, 
                              out List<Customer> customers, 
                              out List<Address> addresses);

CustomerRepository 调用其 GetCustomer 方法,然后调用 CustomerDataAccess.GetCustomerWithAddresses DAL 方法。 DAL 方法然后输出两个 out 参数,一个用于客户,一个用于地址。存储库方法然后使用 AutoMapper 将两个对象从 DAL 方法映射到存储库随后返回的业务域。

这是我目前的代码,但无法正常工作。我的研究并没有帮助我确定我需要做什么来解决这个问题。如何设置我的 out 参数的值?

// Arange
ICustomerDataAccess customerDataAccess = Substitute.For<ICustomerDataAccess>();
IList<Customer> customers;
IList<Address> addresses;

customerDataAccess.When(x => x.GetCustomerWithAddresses(
    1, out customers, out addresses))
    .Do(x =>
    {
        customers = new List<Customer>() { new Customer() { CustomerId = 1, CustomerName = "John Doe" } };
        addresses = new List<Address>() { new Address() { AddressId = 1, AddressLine1 = "123 Main St", City = "Atlanta" } };
    });

CustomerRepository sut = new CustomerRepository(customerDataAccess);

// Act
Customer customer = sut.GetCustomer(1);

// Assert
Assert.IsNotNull(customer);

最佳答案

out 参数使用其参数位置作为索引进行更新。在 Returns documentation for NSubstitute 中对此进行了解释.因此,对于您的特定情况,您正在填充第二个和第三个参数,因此您应该像这样设置您的调用:

customerDataAccess.When(x => x.GetCustomerWithAddresses(1, out customers, out addresses))
.Do(x =>
{
    x[1] = new List<Customer>() { new Customer() { CustomerId = 1, CustomerName = "John Doe" } };
    x[2] = new List<Address>() { new Address() { AddressId = 1, AddressLine1 = "123 Main St", City = "Atlanta" } };
});

关于c# - NSubstitute 模拟一个没有参数的 void 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30329622/

相关文章:

c# - 使用 Visual Studio 和 .NET 的 Angular 2 路由

PHPUnit测试一个函数被调用了多少次

java - 验证错误与验证错误

android - Android测试仪器期间的ClassNotFoundException

c# - 循环中的循环会在 DataTable C# 中创建重复项

c# - Linq 表达式树 Any() 问题

c# - 如何测试 SQL Server 中的存储过程错误

c# - 关于单元测试的好资源?

javascript - QUnit 测试不一致/交替失败

javascript - element.all(locator).first() vs element(locator) 有警告?