Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java mock函数在指定return后返回null_Java_Junit_Mockito - Fatal编程技术网

Java mock函数在指定return后返回null

Java mock函数在指定return后返回null,java,junit,mockito,Java,Junit,Mockito,测试代码 @Mock private RestTemplate restTemplate; @InjectMocks private ServiceClient client; @Test public void getDocument() throws IOException { String fileExtension = "fileextension"; String host = "docserverur

测试代码

    @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而不是模拟响应

试试这个。这应该行得通

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);
您不需要
@injectmock
。这是多余的。最好使用构造函数注入,而不要使用字段注入和
@injectmock

我希望你是被初始化的mock。这件事就这样结束了

MockitoAnnotations.initMocks(this);

这也可以通过一些运行器类(如果您使用的是任何类)来完成。

在新的
响应属性上调用
getBody()
时会发生什么?这就是代码应该做的。它从响应中获取主体。测试时会发生什么?它抛出一个空异常您确定抛出异常而restTemplate不是空的吗?另一种可能是
restTemplate
final
,这意味着您不能模拟它。@SzigyártóMihály是的,当我在行上设置调试器时restTemplate不显示为空,我正在使用
MockitoJUnitRunner
,谢谢你的提示!