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*/)
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.
From a technical point of view MockMvc is not thread-safe and shouldn't be reused.
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.
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*
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With