From Mockito Documentation: Use it to capture argument values for further assertions. Mockito verifies argument values in natural java style: by using an equals() method. This is also the recommended way of matching arguments because it makes tests clean & simple. In some situations though, it is helpful to assert on certain arguments after the actual verification. For example: ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class); verify(mock).doSomething(argument.capture()); assertEquals(“John”, argument.getValue().getName()); Here is a simple example where we test that the JMS producer was called with a particular person object.

Test for testing out the InviteToConference#joinConference method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import org.junit.Before;  
 import org.junit.Test;  
 import org.mockito.ArgumentCaptor;  
 import org.mockito.Captor;  
 import org.mockito.InjectMocks;  
 import org.mockito.Mock;  
 import org.mockito.Mockito;  
 import org.mockito.MockitoAnnotations;  
 import static org.junit.Assert.*;  
 public class InviteConferenceTest {  
 @Mock  
 JmsProducer mockJmsProducer;  
 @Captor  
 private ArgumentCaptor personCaptor;  
 @InjectMocks  
 InviteToConference test=new InviteToConference();  
 @Before  
 public void initMocks()  
 {  
 MockitoAnnotations.initMocks(this);  
 }  
 @Test  
 public void testForArgumentCaptor()  
 {  
 Person newPerson=new Person("Arnab","Mitra");  
 test.joinConference(newPerson);  
 Mockito.verify(mockJmsProducer).sendMessage(personCaptor.capture());  
 Person p=personCaptor.getValue();  
 assertEquals("Arnab", p.getFirstName());  
 assertEquals("Mitra", p.getLastName());  
 }  
 }  
1
2
3
4
5
6
7
8
9
10
11
12
13
public class InviteToConference {  
 private Person person;  
 private JmsProducer jmsProducer;  
 public void joinConference(Person p)  
 {  
 jmsProducer(p);  
 }  
 public void jmsProducer(Person p)  
 {  
 jmsProducer.sendMessage(p);  
 //send a jms message maybe  
 }  
 }  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 public class Person {  
 private String firstName;  
 private String lastName;  
 public String getFirstName() {  
 return firstName;  
 }  
 public void setFirstName(String firstName) {  
 this.firstName = firstName;  
 }  
 public String getLastName() {  
 return lastName;  
 }  
 public void setLastName(String lastName) {  
 this.lastName = lastName;  
 }  
 public Person(String firstName, String lastName) {  
 super();  
 this.firstName = firstName;  
 this.lastName = lastName;  
 }  
 }  
1
2
3
 public interface JmsProducer {  
 public Person sendMessage(Person p);  
 }