2
在this answer中,我使用了REST保證來測試文件的後置操作。控制器是:SpringBoot和REST有保證,在404被拋出時得到406
@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>.
我該如何解決這個問題?
不幸的是,這是沒有問題的。 – JeanValjean