The following setups were not matched - converting JustMock to Moq

3.8k views Asked by At

I am going through this tutorial http://blogs.telerik.com/justteam/posts/13-10-25/30-days-of-tdd-day-17-specifying-order-of-execution-in-mocks in regards to TDD. I am attempting to adapt a JustMock statement to 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();
    }

When the test is ran, I get this exception:

Moq.MockVerificationException : The following setups were not matched:ICustomerService os => os.GetCustomer(a1a0d25c-e14a-4c68-ade9-bc3d7dd5c2bc)

When I change .VerifyAll() to .Verify(), the test passes, but I am uncertain if this is correct.

Question: What is the proper way to adapt this code? Is .VerifyAll() not similiar to .OccursOnce()?

1

There are 1 answers

1
Spock On BEST ANSWER

It seems you are missing the .verifiable on the setup. Also you can avoid any verifiable , just use the mock.Verify at the end. You must also call the mocked instance so the verifable work. https://github.com/Moq/moq4/wiki/Quickstart

Please see 2 approaches below.

    [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));
    }