Following example shows how to do integration testing with Spring @MvcMock and Junit 4.
Controller
package com.logicbig.example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class MyMvcController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String prepareView(Model model) {
model.addAttribute("msg", "Spring quick start!!");
return "my-page";
}
}
Config Class
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyWebConfig {
@Bean
public MyMvcController myMvcController() {
return new MyMvcController();
}
}
Test Class
package com.logicbig.example;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class MyMvcControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
@Test
public void testMyMvcController() throws Exception {
ResultMatcher ok = MockMvcResultMatchers.status().isOk();
ResultMatcher msg = MockMvcResultMatchers.model()
.attribute("msg", "Spring quick start!!");
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/");
this.mockMvc.perform(builder)
.andExpect(ok)
.andExpect(msg);
}
}
Output$ mvn test -Dtest=MyMvcControllerTest [INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for com.logcbig.example:spring-mock-mvc-with-junit-4:war:1.0-SNAPSHOT [WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-war-plugin is missing. @ line 37, column 21 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [INFO] [INFO] ----------< com.logcbig.example:spring-mock-mvc-with-junit-4 >---------- [INFO] Building spring-mock-mvc-with-junit-4 1.0-SNAPSHOT [INFO] from pom.xml [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] --- resources:3.3.1:resources (default-resources) @ spring-mock-mvc-with-junit-4 --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc-testing\spring-mvc-testing-junit-4\spring-mock-mvc-with-junit-4\src\main\resources [INFO] [INFO] --- compiler:3.3:compile (default-compile) @ spring-mock-mvc-with-junit-4 --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- resources:3.3.1:testResources (default-testResources) @ spring-mock-mvc-with-junit-4 --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc-testing\spring-mvc-testing-junit-4\spring-mock-mvc-with-junit-4\src\test\resources [INFO] [INFO] --- compiler:3.3:testCompile (default-testCompile) @ spring-mock-mvc-with-junit-4 --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- surefire:3.2.5:test (default-test) @ spring-mock-mvc-with-junit-4 --- [INFO] Using auto detected provider org.apache.maven.surefire.junit4.JUnit4Provider [WARNING] file.encoding cannot be set as system property, use <argLine>-Dfile.encoding=...</argLine> instead [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.logicbig.example.MyMvcControllerTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.426 s -- in com.logicbig.example.MyMvcControllerTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.138 s [INFO] Finished at: 2026-02-25T11:56:54+08:00 [INFO] ------------------------------------------------------------------------ Feb 25, 2026 11:56:53 AM org.springframework.test.context.web.WebTestContextBootstrapper getDefaultTestExecutionListenerClassNames INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] Feb 25, 2026 11:56:53 AM org.springframework.test.context.web.WebTestContextBootstrapper instantiateListeners INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute] Feb 25, 2026 11:56:53 AM org.springframework.test.context.web.WebTestContextBootstrapper instantiateListeners INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource] Feb 25, 2026 11:56:53 AM org.springframework.test.context.web.WebTestContextBootstrapper getTestExecutionListeners INFO: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@43814d18, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@5c5a1b69, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@3701eaf6, org.springframework.test.context.support.DirtiesContextTestExecutionListener@627551fb] Feb 25, 2026 11:56:53 AM org.springframework.web.context.support.GenericWebApplicationContext prepareRefresh INFO: Refreshing org.springframework.web.context.support.GenericWebApplicationContext@76f2b07d: startup date [Wed Feb 25 11:56:53 CST 2026]; root of context hierarchy Feb 25, 2026 11:56:53 AM org.springframework.mock.web.MockServletContext log INFO: Initializing Spring FrameworkServlet '' Feb 25, 2026 11:56:53 AM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean INFO: FrameworkServlet '': initialization started Feb 25, 2026 11:56:53 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler INFO: Root mapping to handler 'myMvcController' Feb 25, 2026 11:56:54 AM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean INFO: FrameworkServlet '': initialization completed in 88 ms
Example ProjectDependencies and Technologies Used: - spring-webmvc 4.2.4.RELEASE (Spring Web MVC)
- javax.servlet-api 3.0.1 (Java Servlet API)
- spring-test 4.2.4.RELEASE (Spring TestContext Framework)
- junit 4.12 (JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck)
- JDK 1.8
- Maven 3.9.11
|
|