Reputation: 1233
I the class I am testing I have a field, let's call it private List<Person> people
. In the test I want to verify that a certain object with certain states is created. So I need to access that list and the created object in it after I have run the method.
I am using JUnit and Mockito.
Example Test class:
@RunWith(MockitoJUnitRunner.class)
public class Testclass {
@InjectMock
private TestedClass tested;
@Mock(name = "personer")
private List<Person> personerMock;
@Test
public void testMethod() throws BaseException {
PersonA personA = kalle_KMD();
when(personService.getPerson(any(), any())).thenReturn(Optional.of(personA));
Properties p = new Properties();
JobbParametrar params = JobbParametrar.skapa(p);
batch.uppgift(new PersonIdÄrFöretag(1L, false), params, new KörningsId(1L), user);
assertEquals(1, personerMock.size());
}
}
And class to test:
public TestedClass {
private List<Person> persons = Collections.synchronizedList(new ArrayList<Person>());
public void testedMethod() {
...
PersonA personA = personService.getPerson(identitet, användare);
Person p = createPerson(personA);
persons.add(p);
...
}
}
Now, how can I test an object (Person p
) is created an added to the list, and access that object to see its values? Or should I have a totally different approach and not use Mockito in this case?
Mocking the instance field personerMock
, like I did in this example, in the test class doesn't work.
Upvotes: 1
Views: 8417
Reputation: 14999
The way you do it should work, but you need to capture the argument to the add.
ArgumentCaptor<Person> captor = ArgumentCaptor.forClass(Person.class);
verify(personerMock).add(captor.capture());
Person createdPerson = captor.getValue();
// verify the values you're expecting in the person
Upvotes: 1