I want to unit test following method
public void addRecord(Record record)
{
Myclass newObj = new Mycalss();
// It creates newObj object, set some values using record object.
// and it adds the newObj in daatbase.
dataReqDao.persist(newObj);
}
I have mocked dataReqDao.persist method but how can I verify if right values are copied into newObj object? I want to get the newObj object.
I think thenAnswer will be the appropraite method to retrieve newObj ie method arguments but dont know how to use it method which returns void.
Update:
I tried
doAnswer(new Answer<Myclass>() {
public Myclass answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return (Myclass)args[0];
}
}).when(dataReqDao.persist(any(Myclass.class)));
EDIT:
It should be (Thanks David)
doAnswer(new Answer<Myclass>() {
public Myclass answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return (Myclass)args[0];
}
}).when(dataReqDao).persist(any(Myclass.class));
You can create a custom argument matcher that would check fields of that object, or use an argument captor to capture the object for further inspection.
For example, as follows: