代码之家  ›  专栏  ›  技术社区  ›  sf8193

指定return后,模拟函数返回null

  •  0
  • sf8193  · 技术社区  · 6 年前

    测试代码

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

    0 回复  |  直到 6 年前
        1
  •  1
  •   pvpkiran    6 年前

    试试这个。这应该行得通。

    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 .

    我希望你的模拟已经初始化。这是通过以下方式完成的

    MockitoAnnotations.initMocks(this);
    

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