我正在使用Moq来模拟我的Repository层,所以我可以进行单元测试.
我的存储库层插入方法在发生成功的数据库插入时更新我的实体的Id属性.
在调用Insert方法时,如何配置moq以更新实体的Id属性?
存储库代码: -
void IAccountRepository.InsertAccount(AccountEntity account);
单元测试:-
[TestInitialize()] public void MyTestInitialize() { accountRepository = new Mock(); contactRepository = new Mock (); contractRepository = new Mock (); planRepository = new Mock (); generator = new Mock (); 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); }
ContractService类(WCF服务合同)的实现片段.
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 }
如果这些信息可能有点缺乏,我深表歉意.我今天才开始学习moq和模拟框架.AC
您可以使用Callback方法来模拟副作用.就像是:
accountRepository .Expect(r => r.InsertAccount(account)) .Callback(() => account.ID = 1);
这是未经测试的,但它是沿着正确的路线.