【问题标题】:Spring: Test JSP Output in JUnit TestSpring:在 JUnit 测试中测试 JSP 输出
【发布时间】:2016-08-03 01:46:29
【问题描述】:

我们有一个API,它将JSP作为视图返回,例如:

@RequestMapping(value = "/cricket/{matchId}", method = RequestMethod.GET)
    public String getCricketWebView(HttpServletRequest request, @PathVariable("matchId") Integer matchId, ModelMap mv){
        try{

            return "webforms/cricket";

        }catch(Exception e){
            e.printStackTrace();
        }

        return "";
    }

我写了一个单元测试来测试如下:

@Test
    public void test_cricket()
    {
        try {

            MvcResult result =this.mockMvc.perform(get(BASE + "/cricket/123")
                    .accept(MediaType.TEXT_HTML))
                    .andExpect(status().isOk()).andReturn();

            String json = result.getResponse().getContentAsString();

            System.out.println(json);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

问题在于,单元测试只返回字符串webforms/cricket,而不是来自cricket.jsp 页面的实际HTML。我知道发生这种情况是因为我使用的是Mock MVC

但是,有没有一种方法可以测试实际的 HTML?原因是我们使用了一些复杂的JSTL标签,过去我们看到单元测试成功但是实际的JSP页面因为解析失败返回500错误。

我尝试了以下代码:

   try {
            WebConversation conversation = new WebConversation();
            GetMethodWebRequest request = new GetMethodWebRequest(
                    "http://localhost:8080/cricket/123");
            WebResponse response = conversation.getResponse(request);

            System.out.println(response.getResponseMessage());
        }
        catch (Exception e)
        {
            e.printStackTrace();
            org.junit.Assert.fail("500 error");

        }

但这给出了连接被拒绝的异常。我再次理解这是因为在测试时未设置 Web 服务器。

这是我的配置:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/spring-resources/applicationcontext.xml")
public class MobileApiControllerTest {
...
}

我也尝试过使用@WebIntegrationTest,但同样的问题。似乎这只适用于 Spring Boot 应用程序。我们的应用是部署在 Tomcat 上的典型 WAR 应用。

知道如何在单元测试中实现实际的 JSP 输出吗?

【问题讨论】:

  • 我有同样的问题,如果我在我的 jsp (<s:message code="property.key"/>) 中添加一个故障 i18n 属性键,当应用程序在应用程序服务器中运行时我得到状态 500,我得到状态 200当它由 spring mock 运行时。

标签: java spring unit-testing junit jstl


【解决方案1】:

阅读和谷歌搜索我认为使用 Spring Test 框架不会发生这种情况。 Spring 测试不运行 jsp 内的代码(java 代码、jstl、i18n 消息)! This is 也是一个有用的答案。

如果你想测试 jsp 源代码,你必须使用像 Selenium 或 HttpUnit 这样的客户端测试框架。

【讨论】:

    猜你喜欢
    • 2013-02-24
    • 2016-11-30
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 2015-08-07
    相关资源
    最近更新 更多