I have the following situation:
class Worker {
public Integer somework() {
Integer k=0;
Helper h= new Helper();
h.change(k);
return k;
}
}
class Helper {
public void change(Integer k) {
//k = Some calcs
}
}
I'm making unitests for Worker
and obviously I want to mock Helper
class so that his change
method will always put 1 into k
.
My real situation is more complicated but this code represents the issue. Thanks for help.
I have a method with definition like this:
class Template{
public void process(Object rootMap, StringWriter out){
.......
}
}
I will show you how you can change/modify the "out"(StringWriter) reference.
private final Template mocktTemplate = mock(Template.class);
doAnswer(new Answer<StringWriter>() {
public StringWriter answer(InvocationOnMock invocation)
throws Throwable {
Object[] args = invocation.getArguments();
if (args[1] instanceof StringWriter) {
StringWriter stringWriter = (StringWriter) args[1];
stringWriter.write("Email message");
}
return null;
}
}).when(this.mocktTemplate).process(anyObject(),any(StringWriter.class));
Now when you do make the actual call like:
msgBodyTemplate.process(model, msgBodyWriter);
the value of Stringbuffer ref in msgBodyWriter will be "Email message"; irrespective of it earlier value.