Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Spring MockMVC tests, how to chain visit of several webpages?

I have a web application that requires Login. Upon login success, many session attributes are loaded, which will be needed by subsequent navigation of other web pages.

I am testing this web application using Spring test framework 4.12, using MockMVC.

How do I chain a second page visit action after the login page visit? Something like:

mockMvc.perform(post("/login").session(session).param("username", "Jack").param("password","Jack'sPassword"))
               .perform(get("/anotherPage")).andExpect(/*some session attribute are successfully loaded*/)
like image 339
modeller Avatar asked Aug 04 '16 00:08

modeller


People also ask

What kind of testing can be done in spring test module?

2.2. springframework. test. web package contains ModelAndViewAssert , which you can use in combination with JUnit, TestNG, or any other testing framework for unit tests that deal with Spring MVC ModelAndView objects.

Is MockMvc thread safe?

From a technical point of view MockMvc is not thread-safe and shouldn't be reused.

What does MockMvc perform do?

MockMvc provides support for Spring MVC testing. It encapsulates all web application beans and makes them available for testing. We'll initialize the mockMvc object in the @BeforeEach annotated method, so that we don't have to initialize it inside every test.


2 Answers

You can use andDo method to chain your requests

mockMvc.perform(post("/login").session(session)
       .param("username","Jack").param("password","Jack'sPassword"))
       //Expectations on the first request
       .andExpect(status().ok())
       //Then chain the request
       .andDo(
           result -> mockMvc.perform(get("/anotherPage")).andExpect(/*some session    attribute are successfully loaded*
       )
like image 142
Olivier Bearn Avatar answered Sep 29 '22 19:09

Olivier Bearn


In version 5.0.0 you can configure MockMvc to preserve the session between performing calls.

    mvc = MockMvcBuilders
    .webAppContextSetup(context)
    .apply(sharedHttpSession())
    .build();

see: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#spring-mvc-test-server-setup-steps

like image 34
oran g Avatar answered Sep 29 '22 18:09

oran g