📅  最后修改于: 2023-12-03 15:35:35.247000             🧑  作者: Mango
Mockito's verify
method is a powerful tool when it comes to unit testing in Java. It allows you to confirm that a certain method was called with specific arguments during the execution of a test. In this guide, we'll dive into the details of how to use the verify
method effectively.
The most basic usage of verify
is to simply confirm that a method was called during the execution of a test. Here's an example:
// create mock object
List<String> list = Mockito.mock(List.class);
// call method under test
list.add("hello");
// verify that add was called exactly once
Mockito.verify(list).add("hello");
In this example, we create a mock object of the List
class and call its add
method with the argument "hello"
. We then use verify
to confirm that the add
method was called exactly once with the argument "hello"
.
If a method is called multiple times during the execution of a test, you can use the times
argument of verify
to specify how many times it should have been called. Here's an example:
// create mock object
List<String> list = Mockito.mock(List.class);
// call method under test
list.add("hello");
list.add("world");
// verify that add was called twice
Mockito.verify(list, Mockito.times(2)).add(Mockito.anyString());
In this example, we call the add
method twice with different arguments. We use verify
with the times
argument set to 2
to confirm that the add
method was called exactly twice. We also use Mockito.anyString()
as the argument for add
since we don't care about the specific string values.
Using Mockito.any*()
argument matchers allows you to verify that a method was called with any value of a certain type. Here's an example:
// create mock object
List<String> list = Mockito.mock(List.class);
// call method under test
list.add("hello");
list.add("world");
// verify that add was called with any String twice
Mockito.verify(list, Mockito.times(2)).add(Mockito.anyString());
In this example, we use Mockito.anyString()
to match any String
argument passed to the add
method. This allows us to verify that the method was called with any String
argument twice.
In this guide, we covered the basics of using Mockito's verify
method. With this powerful tool, you can easily confirm that certain methods were called with specific arguments during the execution of a test. By using times
arguments and argument matchers, you can make your verifications more precise and increase your unit testing confidence.