关于TDD,我正在阅读本教程http://blogs.telerik.com/justteam/posts/13-10-25/30-days-of-tdd-day-17-specifying-order-of-execution-in-mocks。我试图将一个JustMock语句改编为Moq。
enter code here [Test]
public void testname()
{
var customerId = Guid.NewGuid();
var customerToReturn = new Customer { Id = customerId};
//JustCode
Mock _customerService = Mock.Create<ICustomerService>();
Mock.Arrange(() => _customerService.GetCustomer(customerId)).Returns(customer).OccursOnce();
//Moq
Mock<ICustomerService> _customerService = new Mock <ICustomerService>();
_customerService.Setup(os => os.GetCustomer(customerId)).Returns(customerToReturn);
_customerService.VerifyAll();
}
当测试运行时,我得到了这个例外:
Moq.MockVerificationException : The following setups were not matched:ICustomerService os => os.GetCustomer(a1a0d25c-e14a-4c68-ade9-bc3d7dd5c2bc)
当我将.VerifyAll()更改为.Verify()时,测试通过,但我不确定这是否正确。
问题:适应此代码的正确方法是什么? .VerifyAll()与.OccursOnce()不相似吗?
答案 0 :(得分:2)
您似乎错过了设置上的.verifiable。你也可以避免任何可验证的,只需在最后使用mock.Verify。您还必须调用模拟的实例,以便进行可验证的工作。 https://github.com/Moq/moq4/wiki/Quickstart
请参阅下面的两种方法。
[Test]
public void testname()
{
var customerId = Guid.NewGuid();
var customerToReturn = new Customer { Id = customerId};
//Moq
var _customerService = new Mock <ICustomerService>();
_customerService.Setup(os => os.GetCustomer(customerId)).Returns(customerToReturn).Verifiable();
var cust = _customerService.Object.GetCustomer(customerId);
_customerService.VerifyAll();
}
[Test]
public void testname1()
{
var customerId = Guid.NewGuid();
var customerToReturn = new Customer { Id = customerId };
//Moq
var _customerService = new Mock<ICustomerService>();
_customerService.Setup(os => os.GetCustomer(customerId)).Returns(customerToReturn);
var cust = _customerService.Object.GetCustomer(customerId);
_customerService.Verify(x => x.GetCustomer(customerId));
}