Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking an attribute change on a parameter - using Moq

Tags:

c#

tdd

mocking

moq

I am using Moq to mock my Repository layer so I can unit test.

My repository layer Insert methods update the Id property of my entities when a successful db insert occurs.

How do I configure moq to update the Id property of the entity when the Insert method is called?

Repository code:-

void IAccountRepository.InsertAccount(AccountEntity account);

Unit Test:-

[TestInitialize()]
public void MyTestInitialize() 
{
    accountRepository = new Mock<IAccountRepository>();
    contactRepository = new Mock<IContactRepository>();
    contractRepository = new Mock<IContractRepository>();
    planRepository = new Mock<IPlanRepository>();
    generator = new Mock<NumberGenerator>();

    service = new ContractService(contractRepository.Object, accountRepository.Object, 
                    planRepository.Object, contactRepository.Object, generator.Object);   
}


[TestMethod]
public void SubmitNewContractTest()
{
    // Setup Mock Objects
    planRepository
        .Expect(p => p.GetPlan(1))
        .Returns(new PlanEntity() { Id = 1 });

    generator
        .Expect(p => p.GenerateAccountNumber())
        .Returns("AC0001");

    // Not sure what to do here? 
    // How to mock updating the Id field for Inserts?
    //                                                 
    // Creates a correctly populated NewContractRequest instance
    NewContractRequest request = CreateNewContractRequestFullyPopulated();

    NewContractResponse response = service.SubmitNewContract(request);
    Assert.IsTrue(response.IsSuccessful);
}

implementation snippet from ContractService class (WCF service contract).

AccountEntity account = new AccountEntity()
{
    AccountName = request.Contact.Name,
    AccountNumber = accountNumber,
    BillingMethod = BillingMethod.CreditCard,
    IsInvoiceRoot = true,
    BillingAddressType = BillingAddressType.Postal,
    ContactId = request.Contact.Id.Value
};

accountRepository.InsertAccount(account);
if (account.Id == null)
{
    // ERROR
}

I apologise if this information may be a little lacking. I only started learning moq and mocking frameworks today. ac

like image 575
Rob Gray Avatar asked Jul 24 '26 15:07

Rob Gray


1 Answers

You can use the Callback method to mock side-effects. Something like:

accountRepository
    .Expect(r => r.InsertAccount(account))
    .Callback(() => account.ID = 1);

That's untested but it's along the right lines.

like image 77
Matt Hamilton Avatar answered Jul 26 '26 03:07

Matt Hamilton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!