2 September 2019

Spring MVC test example

  • applicationContext.xml snippet
<bean id="loginAction" class="a.LoginAction" scope="request">
  <property name="username" value="#{request.getParameter('username')}"/>
  <property name="password" value="#{request.getParameter('password')}"/>
  <aop:scoped-proxy/>
</bean>
<bean id="userPreferences" class="a.UserPreferences" scope="session">
  <property name="theme" value="#{session.getAttribute('theme')}"/>
  <aop:scoped-proxy/>
</bean>
<bean id="userService" class="a.UserService">
  <property name="loginAction" ref="loginAction"/>
  <property name="userPreferences" ref="userPreferences"/>
</bean>
  • JUnit test
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:/applicationContext.xml")
public class ScopedBeanTests {

  @Autowired
  private UserService userService;
  @Autowired
  private MockHttpServletRequest httpServletRequest;
  @Autowired
  private MockHttpSession httpSession;

  @Test
  public void testScopedBeans() {
    httpServletRequest.setParameter("username", "jdoe");
    httpServletRequest.setParameter("password", "secret");
    httpSession.setAttribute("theme", "blue");
    Assert.assertEquals("jdoe",userService.getLoginAction().getUsername());
    Assert.assertEquals("secret", userService.getLoginAction().getPassword());
    Assert.assertEquals("blue", httpSession.getAttribute("theme"));
  }
}