SpringBoot和REST保证,在抛出404时获得406

时间:2015-09-03 13:01:13

标签: java exception spring-boot httpresponse rest-assured

this answer中,我使用REST-assured来测试文件的后期操作。控制器是:

@RestController
@RequestMapping("file-upload")
public class MyRESTController {

  @Autowired
  private AService aService;

  @RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  @ResponseStatus(HttpStatus.CREATED)
  public void fileUpload(
      @RequestParam(value = "file", required = true) final MultipartFile file,
      @RequestParam(value = "something", required = true) final String something) {
   aService.doSomethingOnDBWith(file, value);
  }
}

控制器在this answer中进行了测试。

现在我有一个例外:

@ResponseStatus(value=HttpStatus.NOT_FOUND)
public class XNotFoundException extends RuntimeException {

    public XNotFoundException(final String message) {
        super(message);
    }
}

我在服务抛出该异常时测试该情况,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port:0"})
public class ControllerTest{

    {
      System.setProperty("spring.profiles.active", "unit-test");
    }


    @Autowired
    @Spy
    AService aService;

    @Autowired
    @InjectMocks
    MyRESTController controller;

    @Value("${local.server.port}")
    int port;    


  @Before public void setUp(){
    RestAssured.port = port;

    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testFileUpload() throws Exception{
        final File file = getFileFromResource(fileName);

        doThrow(new XNotFoundException("Keep calm, is a test")).when(aService)  
             .doSomethingOnDBWith(any(MultipartFile.class), any(String.class));

        given()
          .multiPart("file", file)
          .multiPart("something", ":(")
          .when().post("/file-upload")
          .then().(HttpStatus.NOT_FOUND.value());
    }
}

但是当我进行测试时,我获得了:

java.lang.AssertionError: Expected status code <404> doesn't match actual status code <406>.

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可能需要将内容类型标题设置为&#34; multipart / form-data&#34;。例如:

given()
       .contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
       .multiPart("file", file)
       .multiPart("something", ":(")
       .when().post("/file-upload")
       .then()...;

如果这不起作用,您可以尝试为单个多部分指定它:

given()
       .multiPart("file", file, MediaType.MULTIPART_FORM_DATA_VALUE)
       .multiPart("something", ":(", MediaType.MULTIPART_FORM_DATA_VALUE)
       .when().post("/file-upload")
       .then()...;