0

我正在阅读本教程http://blogs.telerik.com/justteam/posts/13-10-25/30-days-of-tdd-day-17-specifying-order-of-execution-in-mocks关于TDD。我正在尝试将 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() 不相似吗?

4

1 回答 1

2

您似乎缺少设置中的 .verifiable 。您也可以避免任何可验证的,只需在最后使用 mock.Verify 。您还必须调用模拟实例以便验证工作。 https://github.com/Moq/moq4/wiki/Quickstart

请参阅下面的 2 种方法。

    [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));
    }
于 2013-12-18T01:24:23.947 回答