I am using Mockito for my test class:
@RunWith(SpringRunner.class)
@Import({MyTestContextConfiguration.class})
public class MyWorkerTest extends BaseWorkerTest {
@Spy
protected static MyWorkerImpl externalTaskTopicServiceImpl;
@Before
@SneakyThrows
public void setUp() {
final Similarity similarity0 = Similarity.builder()
.automatic(Boolean.TRUE)
.score(0.555D)
.build();
final MyRequest mpr = MyRequest.builder()
.reference(prod)
.build();
Mockito.doReturn(similarity0).when(externalTaskTopicServiceImpl).invokeMyService(mpr);
//Mockito.when(ReflectionTestUtils.invokeMethod(externalTaskTopicServiceImpl, "invokeMyService", mpr)).thenReturn(similarity0);
}
@SneakyThrows
@Test
public void myTest() {
...
externalTaskTopicServiceImpl.handle(externalTaskService, externalTask);
}
}
MyRequest
an Similarity
are simple POJOs to be handled as JSON by ObjectMapper.
The worker impl class:
@Service
@Slf4j
public class MyWorkerImpl extends WorkerBase {
@Override
public void handle() {
...
final MyRequest mpr = MyRequest.builder().reference(product).build();
invokeMatchProductsService(mpr);
}
protected Similarity invokeMyService(final MyRequest req) throws MyServiceException {
return httpService.matchPopResult(req);
}
}
invokeMatchProductsService
returns always null
when I use Mockito.doReturn()
notation. When I use Mockito.when()
notation a Similarity object is return but in the end the test case fails with:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Similarity cannot be returned by toString()
toString() should return String
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
Can anybody tell me why I am always getting null when using doReturn() as suggested when a spy is stubbed?