gpt4 book ai didi

c# - 模拟参数的属性更改 - 使用 Moq

转载 作者:行者123 更新时间:2023-11-30 14:21:07 27 4
gpt4 key购买 nike

我正在使用 Moq 来模拟我的存储库层,以便我可以进行单元测试。

当成功插入数据库时​​,我的存储库层插入方法会更新我的实体的 Id 属性。

如何配置最小起订量以在调用 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
}

如果这些信息可能有点缺乏,我深表歉意。我今天才开始学习最小起订量和模拟框架。交流

最佳答案

您可以使用回调方法模拟副作用。像这样的东西:

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

那是未经测试的,但它是正确的。

关于c# - 模拟参数的属性更改 - 使用 Moq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/181853/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com