Jigs
Jigs

Reputation: 57

Wanted but not invoked: However, there were other interactions with this mock:

Wanted but not invoked: However, there were other interactions with this mock:

This is a mockito error you would catch when trying to verify the invocation on an object on specific method, but what happens is you have interacted with other method of that object but not the one mentioned. If you have an object named CustomerService and say it has two methods named saveCustomer() and verifyExistingCustomer(), and your mockito looks something like verify(customerService, atleast(1)).verifyExistingCustomer(customer), but in your actual service you called the saveCustomer() at least one.

Any idea how to resolve this ?

Upvotes: 4

Views: 21673

Answers (2)

roxhens
roxhens

Reputation: 552

This probably happened because you shared the mocked object of CustomerService between tests. Such as you might have set up the mock of CustomerService at the @BeforeAll method.

Make sure to clean up after each test or use @BeforeEach so it is recreated before each test.

Upvotes: 0

Caps
Caps

Reputation: 1523

From what you are describing, it looks like you are telling your mocks that you are expecting verifyExistingCustomer() to be called but you are not actually calling it.

You should probably look at your test design, specifically ensuring that you can (via mocking) isolate your tests to test each method individually.

If there is something in your code that decides whether to call saveCustomer() or verifyExistingCustomer() then you should try to mock the data that the code inspects so that you can test each individually.

For example if your code looked like this:

if (customer.getId() == 0) {
 saveCustomer(customer);
} else {
 verifyExistingCustomer(customer);
}

Then you could have two separate tests that you could isolate by setting a zero value and non-zero value for the id in customer.

If you'd like to share your code I could probably give you a better example.

Upvotes: 7

Related Questions