import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@SpringBootTest
public class FileDownloadTest {
@Autowired
private XxxController xxxController;
private MockMvc mockMvc;
@BeforeEach
private void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(xxxController).build();
}
@Test
public void testDownloadFile() throws Exception {
// 1. 执行模拟的GET请求,获取下载文件的接口
MvcResult result = mockMvc.perform(get("/api/download")) // 替换为你的下载接口路径
.andReturn();
// 2. 从结果中获取模拟的HttpServletResponse对象
MockHttpServletResponse response = result.getResponse();
// 3. 从response中获取文件的字节数组
byte[] fileBytes = response.getContentAsByteArray();
// 4. 将字节数组写入本地文件
File localFile = new File("/path/to/your/downloaded_file.pdf"); // 替换为你想要保存的本地路径
try (FileOutputStream fos = new FileOutputStream(localFile)) {
fos.write(fileBytes);
}
// (可选) 可以添加断言,例如检查文件是否存在、大小是否正确等
// assertTrue(localFile.exists());
// assertEquals(expectedSize, localFile.length());
}
}