您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

为@ExceptionHandler编写JUnit测试

为@ExceptionHandler编写JUnit测试

考虑使用Spring 3.2及其mvc-test- framework

import static org.springframework.test.web.servlet.setup.mockmvcBuilders.*;
import static org.springframework.test.web.servlet.request.mockmvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.mockmvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml")
public class WebMvcTest {

    @Autowired
    private WebApplicationContext wac;

    private mockmvc mockmvc;

    @Before
    public void setup() {
        this.mockmvc = mockmvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void getFoo() throws Exception {
        this.mockmvc.perform(
            get("/testx")
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            )
            .andExpect(status().isUnauthorized());
    }
}

控制器代码

@Controller
public class MyController {

    public class MyException extends RuntimeException {
    };

    @RequestMapping("/testx")
    public void myMethod() {
        throw new MyException();

    }

    @ExceptionHandler(MyException.class)
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "blah")
    public void handler() {
        System.out.println("handler processed");
    }
}

此“测试”顺利通过。

免责声明:目前,我在Spring MVC测试中是菜鸟,实际上这是我的第一个测试。

其他 2022/1/1 18:16:55 有636人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶