我想断言引发了一个异常,并且服务器返回了一个500内部服务器错误。
为了突出这一意图,提供了一个代码片段:
thrown.expect(NestedServletException.class);
this.mockMvc.perform(post("/account")
.contentType(MediaType.APPLICATION_JSON)
.content(requestString))
.andExpect(status().isInternalServerError());
当然,我写的是isInternalServerError
还是isOk
都没关系。无论是否在throw.except
语句下方抛出异常,测试都将通过。
你将如何着手解决这个问题?
发布于 2019-07-02 23:34:24
您可以获取对MvcResult和可能已解决的异常的引用,并检查一般的JUnit断言...
MvcResult result = this.mvc.perform(
post("/api/some/endpoint")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(someObject)))
.andDo(print())
.andExpect(status().is4xxClientError())
.andReturn();
Optional<SomeException> someException = Optional.ofNullable((SomeException) result.getResolvedException());
someException.ifPresent( (se) -> assertThat(se, is(notNullValue())));
someException.ifPresent( (se) -> assertThat(se, is(instanceOf(SomeException.class))));
发布于 2020-10-07 21:03:20
我最近遇到了同样的错误,我没有使用MockMVC,而是创建了一个集成测试,如下所示:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = { MyTestConfiguration.class })
public class MyTest {
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void myTest() throws Exception {
ResponseEntity<String> response = testRestTemplate.getForEntity("/test", String.class);
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode(), "unexpected status code");
}
}
和
@Configuration
@EnableAutoConfiguration(exclude = NotDesiredConfiguration.class)
public class MyTestConfiguration {
@RestController
public class TestController {
@GetMapping("/test")
public ResponseEntity<String> get() throws Exception{
throw new Exception("not nice");
}
}
}
这篇文章非常有用:https://github.com/spring-projects/spring-boot/issues/7321
发布于 2018-05-28 18:19:19
在您的控制器中:
throw new Exception("Athlete with same username already exists...");
在您的测试中:
try {
mockMvc.perform(post("/api/athlete").contentType(contentType).
content(TestUtil.convertObjectToJsonBytes(wAthleteFTP)))
.andExpect(status().isInternalServerError())
.andExpect(content().string("Athlete with same username already exists..."))
.andDo(print());
} catch (Exception e){
//sink it
}
https://stackoverflow.com/questions/16605811
复制相似问题