Spring: Test JSP Output in JUnit Test

隐身守侯 提交于 2020-01-03 10:56:10

问题


We have a API, which returns the JSP as the view, for example:

@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 "";
    }

I wrote a unit test to test this out as follows:

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

    }

The problem is that, the unit tests only returns the string webforms/cricket and not the actual HTML from the cricket.jsp page. I understand this is happening because I am using the Mock MVC.

But, is there a way I can test the actual HTML? The reason is that we use some complex JSTL tags and we have seen in the past that unit test succeeds but the actual JSP page returns 500 error because of parsing failure.

I tried the following code:

   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");

        }

But this gives, connection refused exception. Again I understand this is because web server is not setup at the time of test.

This is my configuration:

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

I also tried using @WebIntegrationTest, but the same problem. It seems this only works for Spring boot application. Our application is a typical WAR application deployed on Tomcat.

Any idea how can I achieve the actual JSP output in unit test?


回答1:


Reading and googling I think that this can't happen using the Spring Test framework. Spring test does not run the code(java code, jstl, i18n messages) inside the jsp! This is also a useful answer from so.

If you wish to test the jsp source, you have to use a client side test framework like Selenium or HttpUnit.



来源:https://stackoverflow.com/questions/36573408/spring-test-jsp-output-in-junit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!