Friday 17 May 2013

Modifying Passed Object to a Mocked Interface's Method

For instance we have a mockable interface with a method accepting an object that modifies its property inside without returning back the new property value. The new value however is required by subsequence codes. For example:
public void InsertOrUpdate(Invoice invoice)
{
   . . .
   context.Add<Invoice>(invoice); // this method will save to database and generate an Id
   
   int generatedId = invoice.InvoiceId; // the Id is required for subsequence codes
   . . .
}
Now how do we do this in our unit test with Moq? We can use Callback feature to modify the object passed then go on with our testing:
// Arrange
Mock<IDomainContext> context = new Mock<IDomainContext>();
InvoiceDS invoiceDS = new InvoiceDS(context.Object);
  //set up so that after context.Add<Invoice>(invoice) is called, InvoiceId is set to 5
context.Setup(c => c.Add<Invoice>(It.IsAny<Invoice>())).Callback<Invoice>(i => i.InvoiceId = 5);
Invoice invoice = new Invoice();

// Act
invoiceDS.InsertOrUpdate(invoice);

// Assert
. . .

No comments: