簡體   English   中英

SpringBoot和REST保證,拋出404時得到406

[英]SpringBoot and REST-assured, getting 406 when 404 is thrown

這個答案中 ,我使用了REST保證測試文件的后操作。 控制器是:

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

控制器已按照此答案進行測試。

現在我有一個例外:

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

我該如何解決?

您可能需要將內容類型標頭設置為“ 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()...;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM