40

Let's say i have the following psuedo like test code:

 //Let's import Mockito statically so that the code looks clearer
 import static org.mockito.Mockito.*;

 //mock creation
 List mockedList = mock(List.class);

 //using mock object
 mockedList.add("one");
 mockedList.clear();

 //what do these two verify methods do ?
 verify(mockedList).add("one");
 verify(mockedList).clear();

I keep showing the test passed but i dont know what the verify means ? what is it verifying exactly ? I understand that i mocked a call to add and clear but what does the two verify calls do ?

1
  • 1
    You can also use verify to verify exact number of invocations / at least once / never, or make sure interaction(s) never happened on mock
    – Phat H. VU
    Commented Dec 16, 2014 at 3:12

3 Answers 3

44

Mockito.verify(MockedObject).someMethodOnTheObject(someParametersToTheMethod); verifies that the methods you called on your mocked object are indeed called only once. If they weren't called, or called with the wrong parameters, or called the wrong number of times, they would fail your test.

11

It asserts that the method was called, and with those arguments.

Comment out:

//mockedList.add("one");

Or change its argument and the test will fail.

1
  • 1
    Right, it says org.mockito.exceptions.verification.WantedButNotInvoked, thanks weston. Commented Aug 22, 2020 at 8:23
0

The verify() method in Mockito is used to check if a method of an object was called. It is used to make sure that the method was called with certain parameters, the number of times it was called, etc.

// Example:

// Create a mock object of a class 
MyClass mockClass = Mockito.mock(MyClass.class); 

// Call a method on the mock object 
mockClass.doSomething(); 

// Verify that the doSomething() method was called 
Mockito.verify(mockClass).doSomething();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.