doAnswer() to modify passed objects is not being called for Void method
Use Case:
I want to call a method of mocked class with list of objects and want to
modify passed parameters. It works fine if I work on some method with
return type and doesn't work for Void returning methods.
Method to test:
class toTest{
@Autowired
Activity activity;
public void method2Test(List<ABC> abc)
activity.doActivity(abc);
for(ABC singleABC: abc){
//This was done for testing.
Sysout(singleABC.getActivitySuccessful);
}
}
}
In this example, I want to modify abc to populate one of its boolean
variable to be true/false.
I have added a doAnswer() clause in test case like this:
Test Class:
public class TestMe{
@Mock
Activity activity;
public void test(){
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws
Throwable {
Object[] arguments = invocation.getArguments();
List<URLObject> objs = (List<URLObject>) arguments[0];
//Trying to modify the object's parameter.
objs.get(0).setActivitySuccessful(false);
return null;
}
}).when(activity).doActivity(anyList());
//Some assertions here which fail as object is not modified properly.
}
}
Issue:
If I change the return type of doActivity method to be List<ABC> than
Void, then it gets called and works as expected (without changing the test
code).
Do we need some changes for void methods? I have already set it to return
void in doAnswer.
Any help would be appreciated.
No comments:
Post a Comment