Spring:在JUnit Test中测试JSP输出

Mad*_*uja 6 java junit spring unit-testing jstl

我们有一个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 "";
    }
Run Code Online (Sandbox Code Playgroud)

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

@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();
        }

    }
Run Code Online (Sandbox Code Playgroud)

问题是,单元测试只返回字符串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");

        }
Run Code Online (Sandbox Code Playgroud)

但是这给了连接拒绝例外.我再次理解这是因为在测试时没有设置Web服务器.

这是我的配置:

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

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

任何想法如何在单元测试中实现实际的JSP输出?

Geo*_*lou 3

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

如果您希望测试 jsp 源代码,则必须使用客户端测试框架,例如 Selenium 或 HttpUnit。