Parameter Attribute Change Offset - Using Moq

I use Moq to mock my repository layer so I can unit test.

My repository level Nested methods update the Id property of my objects when a successful db insert occurs.

How to configure moq to update the Id property of an object when calling the Insert method?

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

fragment of implementation from the class ContractService (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
}

We apologize if this information is a bit lacking. I just started learning moq and mocking frameworks today. ace

+3
source share
2 answers

You can use the callback method to simulate side effects. Sort of:

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

This is untested, but it is on the right lines.

+5

, , , , , ID 1.

, , p > 0 IAccountRepository.InsertAccount, bool, . , , ( Id genereated).

, .

accountRepository
    .Expect(p => p.InsertAccount(It.Is<AccountEntity>(x => x.Id == null)))
    .Callback<AccountEntity>(a => a.Id = 1);

.

+2

Source: https://habr.com/ru/post/1698024/


All Articles