繁体   English   中英

NSubstitute使用out参数模拟void方法

[英]NSubstitute mock a void method with out parameters

我是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参数使用其参数位置作为索引进行更新。 它在NSubstituteReturns 文档中有解释 因此,对于您的特定情况,您正在填充第二个和第三个参数,因此您应该像这样设置您的调用:

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

对于非void方法,可以使用常规返回语法:

 var haveWithAddresses = customerDataAccess.GetCustomerWithAddresses(1, out customers, out addresses)
               .Returns(callInfo => { 
                     callInfo[0] = new List<Customer>();
                     callInfo[1] = new List<Address>();
                     return true;
               });

使用Void方法, When...Do语法是正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM