我在测试课上使用Mockito:
@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
和Similarity
是由ObjectMapper作为JSON处理的简单POJO。
工人impl类:
@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
表示法时,null
总是返回Mockito.doReturn()
。当我使用Mockito.when()
表示法时,返回一个Similarity对象,但最后测试用例失败了:
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.
任何人都可以告诉我为什么在使用doReturn()时我总是得到null,因为间谍是间谍?
如果你知道如何正确地做到这一点,那就不难了! ;-)
而不是以这种方式存根:
Mockito.doReturn(similarity0).when(externalTaskTopicServiceImpl).invokeMyService(mpr);
你必须使用Matchers,或者更准确地说,是ArgumentMatchers:
Mockito.doReturn(similarity0).when((MyWorkerImpl)externalTaskTopicServiceImpl).invokeMyService(ArgumentMatchers.any(MyRequest.class));
很明显,错误的存根会导致null,因为在监视externalTaskTopicServiceImpl时,仅在测试用例中/在本地定义的mpr将永远不会在程序执行期间使用。这避免了invokeMyService()
中的空值。
关于org.mockito.exceptions.misusing.WrongTypeOfReturnValue
,这只是我的设计错误:我在spied类中设计了返回ConcurrentHashMap<String, Object>
的方法但是在测试用例中我返回了一个响应对象。