我正在使用 Moq 来模拟我的存储库层,以便进行单元测试。
当数据库插入成功时,我的存储库层插入方法会更新我的实体的 Id 属性。
如何配置 moq 以在调用 Insert 方法时更新实体的 Id 属性?
存储库代码:-
void IAccountRepository.InsertAccount(AccountEntity account);
单元测试:-
[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);
}
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
}
如果这些信息可能有点缺乏,我深表歉意。我今天才开始学习起订量和模拟框架。交流