【问题标题】:Mockito: check response Header and StatusMockito:检查响应标头和状态
【发布时间】:2016-11-10 05:04:41
【问题描述】:

我在 Spring Web 模型-视图-控制器 (MVC) 框架应用程序中使用 Mockito(在 MIT 许可下发布的 Java 开源测试框架)进行了这个 junit 测试 我在控制器中有这个方法:

@RequestMapping(value = { "/devices" } , method = { RequestMethod.GET, RequestMethod.POST} )
    public void initGetForm(@ModelAttribute("searchForm") final SearchForm searchForm,
                            HttpServletRequest request,
                            HttpServletResponse response,
                            Locale locale) throws Exception {

        String newUrl = request.getContextPath() + "/devices/" + locale;

        if (locale !=null && isValid(locale)) {
            newUrl = request.getContextPath() + "/devices/" + DEFAULT_LOCALE;           
        } 

        redirectPermanently (response, newUrl);     

    }




    protected void redirectPermanently (HttpServletResponse response, String to) {

        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location", to);
        response.setHeader("Connection", "close");
        }

这是我的测试课:

@Test
    public void testInitGetForm() throws Exception {

        controller.initGetForm(emptySearchForm(), request, response, null);

    }

@Before
public void setUpTest() {
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
}

是否可以检查响应的标头和状态?????

【问题讨论】:

  • 此测试不使用 Mockito。

标签: java spring-mvc junit


【解决方案1】:

您可以使用 spring-test 模块中的 MockHttpServletResponse 和 MockHttpServletRequest 实例。 将它们传递给您的控制器,然后使用 MockHttpServletResponse.getStatus() MockHttpServletResponse.containsHeader() 检查结果 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多