首页 > 解决方案 > 如何使用junit和mockito测试spring资源文件

问题描述

我在一个spring boot projet中工作,我创建了一个从类路径返回文件的api,一切正常,这是我的api:

@Value(value = "classpath:pdf/notice_file.pdf")
private Resource myPdfResource;

@GetMapping("/getLocalDocument/{typeDoc}")
public ResponseEntity<byte[]> getLocalDocument(@PathVariable String typeDoc)
{
    byte[] contents = new byte[0];

    HttpStatus status = HttpStatus.OK;
    HttpHeaders headers = new HttpHeaders();

    final InputStream in;
    String filename="";

    try {

        headers.setContentType(MediaType.APPLICATION_PDF);

        if ("NOTICE".eqauls(typeDoc)) {
            in = myPdfResource.getInputStream();
            contents = IOUtils.toByteArray(in);
            filename = "notice_1.pdf";
        }

        headers.setContentDispositionFormData(filename, filename);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

        return new ResponseEntity<>(contents, headers, status);

    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

所有测试方法都可以,但我的方法 getLocalDocumentTest 出错,这是我的单元测试代码:

@RunWith(SpringRunner.class)
@PrepareForTest(IOUtils.class)
public class ApiTest{

    @Mock
    private Resource myPdfResource;

    @InjectMocks
    private Api api;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(api).build();
    }

    @Test
    public void getLocalDocumentTest() throws Exception {

        String typeDoc= "NOTICE";
        byte[] contents = new byte[0];
         InputStream stubInputStream = IOUtils.toInputStream("some test data for my input stream", "UTF-8");;

        String URI = "/v1/getLocalDocument/"+typeDoc;

        when(myPdfResource.getInputStream()).thenReturn(stubInputStream);

        PowerMockito.mockStatic(IOUtils.class);
        PowerMockito.when(IOUtils.toByteArray(any(InputStream.class))).thenReturn(contents);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI);

        MvcResult mvcResult = mockMvc.perform(requestBuilder).andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        assertEquals(HttpStatus.OK.value(), response.getStatus());
    }

}

当我运行测试时,我收到以下错误:

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().

你知道为什么我会收到这个错误吗,我是 mockito 框架中的新手

谢谢。

标签: javajunitmockito

解决方案


推荐阅读