gpt4 book ai didi

java - 错误请求错误单元测试多部分 Spring 支架

转载 作者:行者123 更新时间:2023-11-30 06:47:11 25 4
gpt4 key购买 nike

我定义了下一个单元测试来测试用于上传文件的 Controller :

 public class PhenotypeControllerTest extends BaseControllerTest{

private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));

@Before
public void setup() throws Exception {
super.setup();
}

@Test
public void loadPhenotype_success() throws Exception{
//mock uuid generation
UUID idFile = UUID.randomUUID();
//Generate the response
ResponseLoad resp = new ResponseLoad();
resp.setFileIdentifier(idFile);
resp.setStatus(Status.FINISHED);
resp.setDescription(null);

MockMultipartFile phenoFile = new MockMultipartFile("size_trans_20160419_KM2.txt","size_trans_20160419_KM2.txt", ContentType.TEXT_PLAIN.toString(), new FileInputStream("src/test/resources/size_trans_20160419_KM2.txt"));
mockMvc.perform(MockMvcRequestBuilders.fileUpload("/phenotypes/load")
.file(phenoFile))
.andExpect(status().isOk())
.andExpect(content().contentType(this.contentType))
.andExpect(content().json(json(resp)));
}
}

测试的父类(super class)包含注释:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
@TestPropertySource(locations="classpath:application.test.properties")
public abstract class BaseControllerTest {

protected MockMvc mockMvc;

@SuppressWarnings("rawtypes")
protected HttpMessageConverter mappingJackson2HttpMessageConverter;

@Autowired
protected WebApplicationContext webApplicationContext;

@Autowired
void setConverters(HttpMessageConverter<?>[] converters) {

this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream()
.filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter)
.findAny()
.orElse(null);

assertNotNull("the JSON message converter must not be null",
this.mappingJackson2HttpMessageConverter);
}

public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@SuppressWarnings("unchecked")
protected String json(Object o) throws IOException {
MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage();
this.mappingJackson2HttpMessageConverter.write(
o, MediaType.APPLICATION_JSON, mockHttpOutputMessage);
return mockHttpOutputMessage.getBodyAsString();
}
}

当我运行测试时,我收到 400 错误,但使用非多部分请求的其他测试工作正常。 Controller 方法如下:

@ApiOperation(value = "Load Phenotype File", nickname = "loadPhenotype",
tags = {"Phenotypes"} )
@ApiResponses({
@ApiResponse(code = 200, message = "Nice!", response = Response.class),
@ApiResponse(code = 507, message = "Error uploading files")
})
@PostMapping(value="/phenotypes/load", produces = "application/json")
public ResponseEntity<ResponseLoad> uploadPhenotype(
@ApiParam(value="Phenotype File", required=true)
@RequestPart(required = true) MultipartFile file){
//1. Validate parameters
ResponseLoad response = new ResponseLoad();
response.setStatus(Status.FINISHED);
//2. Copy file to /tmp/SNPaware/phenotypes/tmp/<UUID>.pheno
response.setFileIdentifier(UUID.randomUUID());
logger.info("Storage phenotype file with identifier "+response.getFileIdentifier());
storageService.store(file, "tmp/"+response.getFileIdentifier()+".pheno");

return ResponseEntity.ok(response);
}

}

当我像这样向其余 api 发送请求时,它可以正常工作:

curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' {"type":"formData"} 'http://hippo:9087/phenotypes/load'

为什么我在测试中得到 400 分?我在测试中缺少一些配置吗?

最佳答案

问题出在测试中 multipartFile 的定义中。原始名称应与 Controller 中的参数名称(在本例中为文件)匹配。

这个定义解决了问题:

 MockMultipartFile phenoFile = new MockMultipartFile("file", "size_trans_20160419_KM2.txt", ContentType.TEXT_PLAIN.toString(), new FileInputStream("src/test/resources/size_trans_20160419_KM2.txt"));

关于java - 错误请求错误单元测试多部分 Spring 支架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com