【问题标题】:SpringBoot and REST-assured, getting 406 when 404 is thrownSpring Boot 和 REST-assured,当 404 被抛出时得到 406
【发布时间】:2015-09-03 13:01:13
【问题描述】:

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>.

我该如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    您可能需要将内容类型标头设置为“multipart/form-data”。例如:

    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()...;
    

    【讨论】:

    • 很遗憾,这不是问题。
    猜你喜欢
    • 2019-07-18
    • 2018-10-04
    • 2018-05-26
    • 2023-03-17
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多