簡體   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