首页 > 解决方案 > 模拟函数在指定返回后返回 null

问题描述

测试代码

    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    private ServiceClient client;

    @Test
    public void getDocument() throws IOException {
        String fileExtension = "fileextension";
        String host = "docserverurl";
        String path = "path";
        String content = "content";

        client = new ServiceClient(restTemplate, host, fileExtension);
        when(restTemplate.getForEntity(any(), any()))
                .thenReturn(new ResponseEntity(content, HttpStatus.OK));
        assertEquals(content, new String(client.getDocument(path)));
    }

和被测代码

    public byte[] getDocument(String path) throws IOException {
        path = suffixWithExtension(path);
        return restTemplate.getForEntity(docServiceHost + DOC_SERVICE_API_VERSION_DEFAULT + DOCUMENT + path, byte[].class).getBody();
    }

出于某种原因,我遇到了一个问题,当getForEntity在被测函数中调用该函数时,它返回 null 而不是模拟响应。

标签: javajunitmockito

解决方案


试试这个。这应该有效。

byte[] content = "content".getBytes();
when(restTemplate.getForEntity(anyString(), any()))
                .thenReturn(new ResponseEntity(content, HttpStatus.OK));
final byte[] sds = someClass.getDocument("sd");
assertEquals(new String(content), new String(sds));

一些技巧。如果你正在这样做

client = new ServiceClient(restTemplate, host, fileExtension);

你不需要@InjectMocks。这是多余的。使用构造函数注入而不使用字段注入和@InjectMocks.

我希望你是 Mocks 已初始化。这是用

MockitoAnnotations.initMocks(this);

这也可以通过一些 Runner 类完成(如果您正在使用任何类)


推荐阅读