使用Mockito doReturn总是返回null

时间:2019-04-23 12:54:17

标签: null mocking mockito spy

我将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);
    }
}

MyRequestSimilarity是简单的POJO,ObjectMapper会将其作为JSON处理。

worker 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()表示法时,会返回一个相似性对象,但最终测试用例失败,并显示以下内容:

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吗?

1 个答案:

答案 0 :(得分:0)

如果您知道如何正确执行操作,那一点也不难! ;-)

而不是以此方式存根:

Mockito.doReturn(similarity0).when(externalTaskTopicServiceImpl).invokeMyService(mpr);

您必须使用Matchers或更准确地说是ArgumentMatchers:

Mockito.doReturn(similarity0).when((MyWorkerImpl)externalTaskTopicServiceImpl).invokeMyService(ArgumentMatchers.any(MyRequest.class));

很明显,错误的存根会导致null,因为在监视externalTask​​TopicServiceImpl时,仅在测试用例中/在测试用例中本地定义的 mpr 不会在程序执行期间使用。 这样可以避免invokeMyService()中的空值。

关于org.mockito.exceptions.misusing.WrongTypeOfReturnValue,这只是我的设计错误: 我在侦探类中设计了该方法以返回ConcurrentHashMap<String, Object>,但在测试用例中,我返回了一个响应对象。