I think you maybe need a helper class AnswerPipeline
that I will introduce it a moment how to make the test more readable, more expressiveness and more interesting!!!
Note: you can transform any Answer
to AnswerPipeline
by AnswerPipeline#will(Answer)
method, not only returnsFirstArg()
.
THEN using syntax sugar to describe the test, for example:
Function<String, String> function = mock(Function.class);
when(function.apply(anyString())).then(
/**/ will(returnsFirstArg()) // adapt an Answer to an AnswerPipeline
/**/.as(String.class) // set the result type
/**/.to(String::toUpperCase) // transforming the result
);
assertThat(function.apply("first"), equalTo("FIRST"));
AND then it is easy to solving your problem with no difficulty:
when(myMock.myFunction(anyString()))
.then(will(returnsFirstArg()).as(String.class).to(MyObject::new));
AnswerPipeline class
interface AnswerPipeline<T> extends Answer<T> {
static <R> AnswerPipeline<R> will(Answer<R> answer) {
return answer::answer;
}
default <R> AnswerPipeline<R> as(Class<R> type) {
return to(type::cast);
}
default <R> AnswerPipeline<R> to(Function<T, R> mapper) {
return it -> mapper.apply(answer(it));
}
}