DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. JUnit Testing of Spring MVC Application: Testing Controller

JUnit Testing of Spring MVC Application: Testing Controller

Krishna Prasad user avatar by
Krishna Prasad
·
Mar. 04, 13 · Interview
Like (3)
Save
Tweet
Share
108.70K Views

Join the DZone community and get the full member experience.

Join For Free

In continuation of my earlier blogs on Introduction to Spring MVC and Testing Service layer in Spring MVC, in this blog I will demonstrate how to test Controller in Spring MVC. The objective of this demo is 2 fold, to build the Controller layer using TDD and increase the code coverage during JUnit testing of Controller.

For people in hurry, get the latest code from Github and run the below command

mvn clean test -Dtest=com.example.bookstore.web.controller.SpringMvcTestLoginControllerTest

Since in my earlier blog, we have already tested and implemented Service layer, in this blog we only need to focus on testing Controller. For testing the Controller I will use Spring-Test-MVC framework, which I have discussed enough in my earlier blogs. Spring-test-MVC implements a Domain Specific Language (DSL) for testing the Controller.

As a first step we define the LoginControllerTestConfiguration class with LoginControllerTest class. If you notice there are 2 beans defined in that class and we marked the as a @Configuration which shows that it is a Spring Context class. In the JUnit test we @Autowired LoginController class and @Autowired AccountService class. When creating the Bean in the configuration file we also stubbed the AccountService class using Mockito,

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SpringMvcTestLoginControllerTest {

@Configuration
static class LoginControllerTestConfiguration {

@Bean
public AccountService accountService() {
return Mockito.mock(AccountService.class);
}

@Bean
public LoginController loginController() {
return new LoginController();
}
}
@Autowired
private LoginController loginController;

@Autowired
private AccountService accountService;
}

As a next step let us setup the data. If you notice the below code, we have also stubbed AccountService’s login method to return pre-configured data using Mockito.

@Before
public void setup() throws Exception {
this.account = new AccountBuilder() {
{
address("Herve", "4650", "Rue de la station", "1", null, "Belgium");
credentials("john", "secret");
name("John", "Doe");
}
}.build(true);

Mockito.when(this.accountService.login("john", "secret")).thenReturn(this.account);
}

Next we write the test where we set the loginController to the MockMvcBuilders and use Spring-test-MVC’s DSL to call the controller layer and do the asserts. Now if you run the test it will succeed.

@Test
public void testHandleLogin() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(this.loginController).build();
mockMvc.perform(post("/login").param("username", "john").param("password", "secret"))
.andExpect(status().isOk())
.andExpect(request().sessionAttribute(LoginController.ACCOUNT_ATTRIBUTE, this.account))
.andExpect(redirectedUrl("/index.htm"));
}

Finally, loginController looks as below,

@Controller
@RequestMapping(value = "/login")
public class LoginController {

@Autowired
private AccountService accountService;

@RequestMapping(method = RequestMethod.POST)
public String handleLogin(@RequestParam String username, @RequestParam String password, HttpSession session)
throws AuthenticationException {
Account account = this.accountService.login(username, password);
session.setAttribute(ACCOUNT_ATTRIBUTE, account);
String url = (String) session.getAttribute(REQUESTED_URL);
session.removeAttribute(REQUESTED_URL); // Remove the attribute
if (StringUtils.hasText(url) && !url.contains("login")) { // Prevent loops for the login page.
return "redirect:" + url;
} else {
return "redirect:/index.htm";
}
}
}

I hope this blog helped you. In my next blog we will implement the web layer.




 

Spring Framework JUnit application Domain-Specific Language

Published at DZone with permission of Krishna Prasad, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Handling Automatic ID Generation in PostgreSQL With Node.js and Sequelize
  • Integration: Data, Security, Challenges, and Best Solutions
  • Explaining: MVP vs. PoC vs. Prototype
  • Internal Components of Apache ZooKeeper and Their Importance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: