如何解决为什么 WireMock 不写入文件内容?
...
@GetMapping("/{id}/download")
public ResponseEntity<streamingresponsebody> downloadFile(@PathVariable Long id,HttpServletResponse response) {
MyFile file = fileService.getFileInfo(id);
String filename = file.getoriginalFileName();
response.setContentType(MediaType.parseMediaType(fileAssociation.getMimeType()).toString());
response.setHeader(HttpHeaders.CONTENT_disPOSITION,"attachment; filename=\"" + filename + "\"");
streamingresponsebody stream = out -> {
InputStream in = fileServiceService.loadFileAsResource(id);
byte[] bytes = new byte[1024];
int length;
while ((length = in.read(bytes)) >= 0) {
response.getoutputStream().write(bytes,length);
}
in.close();
};
return new ResponseEntity<>(stream,HttpStatus.OK);
}
...
在另一个应用程序中,我使用 Spring Cloud OpenFeign 通过 GET 请求下载文件:
@FeignClient(name="api-gateway",url="${feign.client.url}")
public interface Proxy {
@GetMapping("/files/{id}/download")
Response dowloadFile(@PathVariable("id") Long id);
}
private Path downloadFile(MyFile file) {
if (!workingDir.equals("/tmp")) {
Utils.createDirectory(workingDir);
}
Path targetLocation = null;
Response response = proxy.dowloadFile(file.getId());
int status = response.status();
if (status == HttpStatus.OK.value()) {
String fileName = file.getoriginalFileName();
Response.Body body = response.body();
try {
InputStream inputStream = body.asInputStream();
targetLocation = Paths.get(workingDir,Utils.generateName(fileName));
Files.copy(inputStream,targetLocation,StandardcopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new StorageException(String.format("Cannot copy into '%s'",targetLocation));
}
} else {
throw new MyException(String.format("ERROR in file '%s': %s. DOWNLOAD ERROR. Response status: %d",file.getoriginalFileName(),file.getJobId(),status));
}
return targetLocation;
}
在 this 之后,我正在尝试使用 wiremock 测试应用程序,并且我有应该返回模拟文件的方法:
...
public static void setupMockFile(wiremockServer mockService) throws IOException {
mockService.stubFor(wiremock.get(wiremock.urlEqualTo("/files/1/download"))
.willReturn(wiremock.aResponse()
.withStatus(HttpStatus.OK.value())
.withHeader("Content-Type","text/csv;charset=UTF-8")
.withHeader(HttpHeaders.CONTENT_disPOSITION,"attachment; filename=\"" + "myfile.csv" + "\"")
.withBodyFile("myfile.csv") // correct location inside resource folder!
));
}
...
在测试类中注册:
...
@BeforeEach
void setUp() throws IOException {
ProxyMocks.setupMockFile(mockProxyService);
}
...
但是当我尝试执行测试时,即使正确创建了文件,文件为空并且日志显示:
2021-04-22 23:02:34.000 INFO 585791 --- [qtp991674862-27] w.o.e.j.s.handler.ContextHandler.ROOT : RequestHandlerClass from context returned com.github.tomakehurst.wiremock.http.StubRequestHandler. normalized mapped under returned 'null'
可能是什么问题?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。