【问题标题】:Bad request error unit test multipart spring rest错误请求错误单元测试多部分弹簧休息
【发布时间】:2017-09-16 18:58:27
【问题描述】:

我有下一个单元测试定义来测试一个用于上传文件的控制器:

 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)));
        }
    }

测试的超类包含注解:

@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 错误,但使用非多部分请求的其他测试工作正常。控制器方法如下:

@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 '接受:应用程序/json' {"type":"formData"} 'http://hippo:9087/phenotypes/load'

为什么我在测试中收到 400 分?我是否在测试中遗漏了一些配置?

【问题讨论】:

    标签: java spring rest unit-testing spring-boot


    【解决方案1】:

    问题出在测试中 multipartFile 的定义中。原始名称应与控制器中的参数名称匹配,在本例中为文件。

    这个定义解决了问题:

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

    【讨论】:

    • @jannis 直到明天我才能将答案标记为已接受,因为我回答了自己的问题(stackoverflow 的限制)。
    • 是的,我不知道。有道理
    猜你喜欢
    • 1970-01-01
    • 2015-12-14
    • 2014-02-06
    • 1970-01-01
    • 2017-12-28
    • 2013-10-02
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多