前提・実現したいこと
ファイルをダウンロードするAPIのJUnitテストを作成しています。
APIを呼び出すとダウンロードダイアログが表示されることを想定していました。
(この記事を参考にしました。https://code.yamarou.com/file-download-servlet/)
発生している問題・エラーメッセージ
JUnit実行後のresponseから、生成したファイルを取得することはできるのですが、
ダウンロードダイアログが表示されません。リクエスト、レスポンスがmockだからでしょうか?
該当のソースコード
DownloadApi.java
java
1@RestController 2public class DownloadApi { 3 @Autowired 4 JdbcTemplate jdbcTemplate; 5 6 @RequestMapping(value = "/api/downloadText", method = org.springframework.web.bind.annotation.RequestMethod.GET) 7 public void downloadText(HttpServletRequest request, HttpServletResponse response) throws Exception { 8 9 response.setContentType("application/octet-stream"); 10 response.setHeader("Content-Disposition", "attachment; filename=\"downloadFile.txt\""); 11 OutputStream out = response.getOutputStream(); 12 try { 13 byte[] data = "テストデータ".getBytes(); 14 out.write(data); 15 } finally { 16 out.close(); 17 } 18 } 19}
JUnitテストコード
java
1import org.junit.Before; 2import org.junit.Test; 3import org.junit.runner.RunWith; 4import org.mockito.InjectMocks; 5import org.mockito.Mock; 6import org.mockito.MockitoAnnotations; 7import org.springframework.beans.factory.annotation.Autowired; 8import org.springframework.jdbc.core.JdbcTemplate; 9import org.springframework.mock.web.MockHttpServletRequest; 10import org.springframework.mock.web.MockHttpServletResponse; 11import org.springframework.test.context.ContextConfiguration; 12import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 13import org.springframework.test.context.web.WebAppConfiguration; 14 15 16@RunWith(SpringJUnit4ClassRunner.class) 17@ContextConfiguration(locations = { "classpath:applicationTestContext.xml" }) 18@WebAppConfiguration 19public class DownloadApiTest { 20 21 @Mock 22 private JdbcTemplate jdbcTemplate; 23 24 @Autowired 25 @InjectMocks 26 DownloadApi downloadApi; 27 28 private MockHttpServletRequest req; 29 private MockHttpServletResponse res; 30 31 @Before 32 public void initialize() { 33 MockitoAnnotations.initMocks(this); 34 // mock request/responseの作成 35 req = new MockHttpServletRequest(); 36 res = new MockHttpServletResponse(); 37 } 38 39 /** 40 * 41 * @throws Exception 42 */ 43 @Test 44 public void test1() throws Exception { 45 46 req.setMethod("GET"); 47 req.setContentType("application/json"); 48 49 // テスト対象コントローラ実行 50 downloadApi.downloadText(req, res); 51 52 // responseから取得 53 res.getOutputStream(); 54 res.getHeader("Content-Disposition"); 55 56 File file = new File("testData.txt"); 57 FileOutputStream responceOutputStream = new FileOutputStream(file); 58 responceOutputStream.write(res.getContentAsByteArray()); 59 responceOutputStream.close(); 60 61 } 62} 63
補足情報(FW/ツールのバージョンなど)
FW:springframework 5.0.3
宜しくお願いします。
あなたの回答
tips
プレビュー