簡體   English   中英

如何使用MockMvc測試具有流式內容的控制器?

[英]How to test a controller with streamed content with MockMvc?

我想使用MockMvc測試沒有Spring上下文的Spring控制器。 該控制器通過將內容寫入響應的OutputStream中傳輸內容。

這是控制器代碼:

@RequestMapping(method = GET, value = "/file")
public void getFile(HttpServletResponse response) throws IOException {
    response.setHeader("Content-Disposition", "attachment; filename=file.json");
    ObjectWriter objectWriter = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL).writer();

    Item item = new Item();
    List<Item> items = new ArrayList<>();
    items.add(item);

    try (Writer bufferedWriter = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()))) {
        objectWriter.writeValue(bufferedWriter, items);
        bufferedWriter.flush();
    }
}

這是測試:

@Test
public void getFile_ok() throws Exception {
    mockMvc.perform(get(END_POINT + "/file").accept(MediaType.APPLICATION_JSON))
           .andExpect(status().isOk());
}

該控制器運行良好,但是單元測試失敗並出現IOException:

java.io.IOException: Stream closed
    at java.io.BufferedWriter.ensureOpen(BufferedWriter.java:116)
    at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:126)
    at java.io.BufferedWriter.flush(BufferedWriter.java:253)

實際上是objectWriter.writeValue(bufferedWriter, items); 嘗試關閉流。

的Javadoc:

注意:方法不會在此處顯式關閉基礎流; 但是,此映射器使用的JsonFactory可能會根據其設置選擇關閉流(默認情況下,當我們構造的JsonGenerator關閉時,它將嘗試關閉流)。

在運行時,它不會關閉它,但是在我的測試中會關閉它,並且下一行bufferedWriter.flush(); 只是發送IOEception

因此,要解決此問題,我以這種方式添加了try / catch:

try {
    writer.flush();
} catch (IOException e) {
    logger.info("Stream closed in writeValue()", e);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM