首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >MockMVC如何在同一测试用例中测试异常和响应代码

MockMVC如何在同一测试用例中测试异常和响应代码
EN

Stack Overflow用户
提问于 2013-05-17 17:33:01
回答 3查看 51K关注 0票数 26

我想断言引发了一个异常,并且服务器返回了一个500内部服务器错误。

为了突出这一意图,提供了一个代码片段:

代码语言:javascript
复制
thrown.expect(NestedServletException.class);
this.mockMvc.perform(post("/account")
            .contentType(MediaType.APPLICATION_JSON)
            .content(requestString))
            .andExpect(status().isInternalServerError());

当然,我写的是isInternalServerError还是isOk都没关系。无论是否在throw.except语句下方抛出异常,测试都将通过。

你将如何着手解决这个问题?

EN

回答 3

Stack Overflow用户

发布于 2019-07-02 23:34:24

您可以获取对MvcResult和可能已解决的异常的引用,并检查一般的JUnit断言...

代码语言:javascript
复制
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))));
票数 12
EN

Stack Overflow用户

发布于 2020-10-07 21:03:20

我最近遇到了同样的错误,我没有使用MockMVC,而是创建了一个集成测试,如下所示:

代码语言:javascript
复制
@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");
        
    }   
}

代码语言:javascript
复制
@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

票数 0
EN

Stack Overflow用户

发布于 2018-05-28 18:19:19

在您的控制器中:

代码语言:javascript
复制
throw new Exception("Athlete with same username already exists...");

在您的测试中:

代码语言:javascript
复制
    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
    }
票数 -7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16605811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档