java - 如何使用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 框架中的新手
谢谢。
解决方案
推荐阅读
- ibm-integration-bus - IBM App Connect Enterprise - 使用 ESQL 删除默认标头
- python - 如果python dict get方法不匹配如何通过
- reactjs - 将 Wordpress 列表页面与单独的反应仪表板结合起来是个好主意吗?
- python - python UTC日期和sqlalchemy
- java - 如何停止绑定到 kafka 集群的消费者组,然后以编程方式重置/移动它的偏移量
- c# - 反序列化 Json 响应
- eclipse - 在 jetty 10/11 版本中找不到 start.ini
- python - 出于某种原因,我的代码分配了变量,但随后它们更改为原始值
- javascript - 如何在 JS 的 firebase 集合中添加文档?
- esp32 - ESP32 esp-idf sdkconfig.ci 文件是做什么用的?