NSubstitute mock a void method with out parameters
Solution 1
out
parameters are updated using their parameter position as an index. It's explained in the Returns
documentation for NSubstitute. So, for your particular case, you are populating the second and third parameters, so you should be setting up your call like this:
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" } };
});
Solution 2
For non-void methods the regular return syntax can be used:
var haveWithAddresses = customerDataAccess.GetCustomerWithAddresses(1, out customers, out addresses)
.Returns(callInfo => {
callInfo[0] = new List<Customer>();
callInfo[1] = new List<Address>();
return true;
});
With Void
methods the When...Do
syntax is correct.
NathanFisherSdk
.NET Developer since 2002. Entity Framework technologist and data-tier development specialist. Advocate and student of S.O.L.I.D, DDD, TDD, and patterns & practices.
Updated on June 05, 2022Comments
-
NathanFisherSdk almost 2 years
I am new to NSubstitute, I am trying to mock a
void
method with 2out
parameters and I am pretty sure I am doing it wrong.I have a
CustomerDataAccess
class that has a method with the following signature:void GetCustomerWithAddresses(int customerId, out List<Customer> customers, out List<Address> addresses);
The
CustomerRepository
calls itsGetCustomer
method which then calls theCustomerDataAccess.GetCustomerWithAddresses
DAL method. The DAL method then outputs twoout
parameters one for the customer and one for addresses. The repository method then usesAutoMapper
to map the two objects from the DAL method to a business domain which the repository then returns.Here is the code I have so far and it is not working. My research hasn't helped me to identify what I need to do to fix this issue. How do I set the value of my
out
parameters?// 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);
-
NathanFisherSdk about 9 yearsYep that worked i was missing accessing the specific parameters in the array.