简体   繁体   中英

mockito mock verify

//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();

//verification
verify(mockedList).add("one");
verify(mockedList).clear();

I don't understand what is the point of this construct? How does it help? How is it different from just calling the functions?
The documentation is rather thin.
Thank you

When you do mockedList.add("one"); its performing the operation on the mocked object as same time it remembers your operation. So when you do verify(mockedList).add("one"); , it verifies the add was called on mockedList with argument one .

Hope you get the difference.

You wish to test that some method Foo of class A calls some method Bar on an object of class B. In other words, you're testing class A. During your test, you make a mock of class B. Then you pass this mock object to class A somehow (depending on how class A actually works). When your test runs the Foo method of class A, you are expecting the Bar method to get called on your mock of class B. By calling verify for the Bar method, after the test of the Foo method, you can check that the Foo method is actually working correctly - that it calls Bar .

the verify method of mockito is verify the method invoke times,if the invoke time is 1,we can omit this parameter, see the source code of Mockito Line 1473

public static <T> T verify(T mock) {
    return MOCKITO_CORE.verify(mock, times(1));
}

so you code

verify(mockedList).add("one");
//is the same as
verify(mockedList,times(1)).add("one");

is indeed to verify the add method's executed once

Indeed in your example it's obvious, but main idea of verifying methods calls appear during real code testing - imagine that some code performs method call like:

class A{
 ....
 service.doSomething(<some arguments>)
 ....
}

In order to test it you'll pass mock service object, but sometimes you want to verify particular arguments values passed for that call (or number of calls), so you'll use verify like in your example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM