Java Micronaut测试文件上传
我想测试一个方法,它接收一个CompletedFileUploadJava Micronaut测试文件上传,java,mocking,micronaut,Java,Mocking,Micronaut,我想测试一个方法,它接收一个CompletedFileUpload public void uploadZip(String orderId, CompletedFileUpload fileUpload) throws IOException { Path path = Files.createTempFile("file-", "-temp"); File tempFile = path.toFile(); try (File
public void uploadZip(String orderId, CompletedFileUpload fileUpload) throws IOException {
Path path = Files.createTempFile("file-", "-temp");
File tempFile = path.toFile();
try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
outputStream.write(fileUpload.getBytes());
someMethod(orderId, tempFile);
}
}
CompletedFileUpload是一个接口:
package io.micronaut.http.multipart;
public interface CompletedFileUpload extends FileUpload, CompletedPart {
}
我想找到一种模拟文件上传的方法,对于spring boot,我发现:
MockMultipartFile multipartFile =
new MockMultipartFile("springboot.png", "springboot.png", "image/png", "".getBytes());
我可以在Micronaut中使用类似的东西吗?您可以像Spring那样构建自己的MockFileUpload测试类:
public class MockFileUpload implements CompletedFileUpload {
private final String filename;
private final MediaType mediaType;
private final byte[] content;
public MockFileUpload(String filename, MediaType mediaType) {
this(filename, mediaType, null);
}
public MockFileUpload(String filename, MediaType mediaType, @Nullable byte[] content) {
this.filename = filename;
this.mediaType = mediaType;
this.content = (content != null ? content : new byte[0]);
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(content);
}
@Override
public byte[] getBytes() throws IOException {
return content;
}
@Override
public ByteBuffer getByteBuffer() throws IOException {
return ByteBuffer.wrap(content);
}
@Override
public Optional<MediaType> getContentType() {
return Optional.of(mediaType);
}
@Override
public String getName() {
return filename;
}
@Override
public String getFilename() {
return filename;
}
@Override
public long getSize() {
return content.length;
}
@Override
public long getDefinedSize() {
return content.length;
}
@Override
public boolean isComplete() {
return true;
}
}
public类MockFileUpload实现CompletedFileUpload{
私有最终字符串文件名;
私有最终MediaType MediaType;
私有最终字节[]内容;
公共MockFileUpload(字符串文件名,MediaType MediaType){
这(文件名、媒体类型、null);
}
公共MockFileUpload(字符串文件名、MediaType、MediaType、@Nullable byte[]内容){
this.filename=文件名;
this.mediaType=mediaType;
this.content=(content!=null?内容:新字节[0]);
}
@凌驾
公共InputStream getInputStream()引发IOException{
返回新的ByteArrayInputStream(内容);
}
@凌驾
公共字节[]getBytes()引发IOException{
返回内容;
}
@凌驾
public ByteBuffer getByteBuffer()引发IOException{
返回ByteBuffer.wrap(内容);
}
@凌驾
公共可选getContentType(){
返回可选的.of(mediaType);
}
@凌驾
公共字符串getName(){
返回文件名;
}
@凌驾
公共字符串getFilename(){
返回文件名;
}
@凌驾
公共长getSize(){
返回content.length;
}
@凌驾
公共长getDefinedSize(){
返回content.length;
}
@凌驾
公共布尔值isComplete(){
返回true;
}
}
然后在测试中,您可以这样使用该类:
CompletedFileUpload file=newmockfileupload(“invoice.pdf”、MediaType.APPLICATION\u pdf\u TYPE)代码>