【发布时间】: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