Spring MVC Controller JUnit Testing

JUnit testing Spring MVC controllers is not an easy task. But recently, a new project (to be included in Spring soon) offers new tools to facilitate this. This post illustrates how to test a simple controller via JUnit tests.

This code is a variation of the code used in JUnit Testing Spring Service and DAO (with In-Memory Database). It is available from Gihut in the Spring-MVC-JUnit-Testing directory.

Test Configuration Classes

These are identical to those required for Service and DAO testing.

Controller

Our controller:

@Controller
public class MyController {

    @Autowired
    private MyService myService;

    @RequestMapping(value = '/')
    public String home(Model model) {

        return 'index';

    }

    @RequestMapping(value = '/roundtrip')
    public String persistenceStatus(Model model) {

        MilliTimeItem retr = myService.createAndRetrieve();
        model.addAttribute('RoundTrip', retr);

        return 'roundtrip';

    }

}


Controller Testing

The following creates an instance of MockMvc to test simulated user requests:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ JpaTestConfig.class, TestConfig.class })
public class MyControllerTest {

    private MockMvc mockMvc;

    @Before
    public void setup() {

        mockMvc = MockMvcBuilders
            .annotationConfigSetup(JpaTestConfig.class, TestConfig.class)
            .build();

    }

    @Test
    public void testHome() throws Exception {

        mockMvc.perform(get('/'))
            .andExpect(status().isOk())
            .andExpect(forwardedUrl('WEB-INF/pages/index.jsp'));

    }

    @Test
    public void testPersistenceStatus() throws Exception {

        mockMvc.perform(get('/roundtrip'))
            .andExpect(status().isOk())
            .andExpect(forwardedUrl('WEB-INF/pages/roundtrip.jsp'))
            .andExpect(model().attributeExists('RoundTrip'));

    }

}

The / request tests the returned status and the URL mapping to the JSP page. The /roundtrip request makes sure the returned model does contain the Roundtrip attribute.

Dependencies

The Spring MVC test artifact is not yet available from maven’s central repository. It should be obtained from another repository:

<repositories>
    <repository>
        <id>spring.test-mvc</id>
            <url>http://repo.springsource.org/libs-milestone</url>
        </repository>
    </repositories>

The required dependency are:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test-mvc</artifactId>
    <version>1.0.0.M1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

More Spring related posts here.

Reference: Spring MVC Controller JUnit Testing from our JCG partner Jerome Versrynge at the Technical Notes blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


− seven = 2



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close