title: MockMvc to test SpringMVC Rest Web Service using JUnit, Mockito, and Hamcrest
body: <p>Am using Spring MVC to create Restful Web Services...</p>
  
  <p>Here's my pom.xml:</p>
  
  <pre><code>&lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
      &lt;version&gt;4.0.3.RELEASE&lt;/version&gt;
  &lt;/dependency&gt;
  
  &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
      &lt;version&gt;4.0.3.RELEASE&lt;/version&gt;
      &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
  
  &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
      &lt;version&gt;4.0.3.RELEASE&lt;/version&gt;
  &lt;/dependency&gt;
  
  &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
      &lt;version&gt;4.0.3.RELEASE&lt;/version&gt;
  &lt;/dependency&gt;
  
  &lt;dependency&gt;
      &lt;groupId&gt;junit&lt;/groupId&gt;
      &lt;artifactId&gt;junit&lt;/artifactId&gt;
      &lt;version&gt;4.12&lt;/version&gt;
      &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
  
  &lt;dependency&gt;
      &lt;groupId&gt;org.hamcrest&lt;/groupId&gt;
      &lt;artifactId&gt;hamcrest-all&lt;/artifactId&gt;
      &lt;version&gt;1.3&lt;/version&gt;
      &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
  
  &lt;dependency&gt;
      &lt;groupId&gt;org.mockito&lt;/groupId&gt;
      &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
      &lt;version&gt;1.10.19&lt;/version&gt;
      &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
  
  &lt;dependency&gt;
      &lt;groupId&gt;com.jayway.jsonpath&lt;/groupId&gt;
      &lt;artifactId&gt;json-path-assert&lt;/artifactId&gt;
      &lt;version&gt;0.9.1&lt;/version&gt;
      &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
  </code></pre>
  
  <p>WEB-INF/web.xml:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;web-app id="WebApp_ID" version="2.4"
      xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt;
      &lt;display-name&gt;MyApp&lt;/display-name&gt;
      &lt;welcome-file-list&gt;
          &lt;welcome-file&gt;index.html&lt;/welcome-file&gt;
          &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
      &lt;/welcome-file-list&gt;
      &lt;servlet&gt;
  
          &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt;
          &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
          &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
      &lt;/servlet&gt;
      &lt;servlet-mapping&gt;
          &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt;
          &lt;url-pattern&gt;/&lt;/url-pattern&gt;
      &lt;/servlet-mapping&gt;
  
      &lt;context-param&gt;
          &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
          &lt;param-value&gt;/WEB-INF/mvc-dispatcher-servlet.xml&lt;/param-value&gt;
      &lt;/context-param&gt;
  &lt;/web-app&gt;
  </code></pre>
  
  <p>WEB-INF/mvc-dispatcher-servlet.xml:</p>
  
  <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans"
      &lt;import resource="classpath:database_db.xml" /&gt;
  
      &lt;context:component-scan base-package="com.myapp.rest" /&gt;
      &lt;mvc:annotation-driven /&gt;
  
      &lt;bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;
          &lt;property name="prefix"&gt;
              &lt;value&gt;/WEB-INF/pages/&lt;/value&gt;
          &lt;/property&gt;
          &lt;property name="suffix"&gt;
              &lt;value&gt;.jsp&lt;/value&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
  &lt;/beans&gt;
  </code></pre>
  
  <p>src/main/resources/database_db.xml:</p>
  
  <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans"&gt;
      &lt;bean id="dataSourceDB"  class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt;
          &lt;property name="driverClassName"&gt;&lt;value&gt;com.mysql.jdbc.Driver&lt;/value&gt;&lt;/property&gt;
          &lt;property name="url"&gt;&lt;value&gt;jdbc:mysql://localhost/mydatabase?zeroDateTimeBehavior=convertToNull&lt;/value&gt;&lt;/property&gt;
          &lt;property name="username"&gt;&lt;value&gt;root&lt;/value&gt;&lt;/property&gt;
          &lt;property name="password"&gt;&lt;value&gt;&lt;/value&gt;&lt;/property&gt;
      &lt;/bean&gt; 
  &lt;/beans&gt;
  </code></pre>
  
  <p>UserController:</p>
  
  <pre><code>@Controller
  @RequestMapping("/v2")
  public class UserController {
  
      private final UserDAO dao;
  
      @Autowired 
      public UserController(UserDAO dao) {
          this.dao = dao;
      }
  
      @RequestMapping(value = "users/appId", method = RequestMethod.GET)
      public @ResponseBody Object getUserDetails(@PathVariable String appId) {
          Object response = null;
          response = dao.getUser(appId);
          return response;
      }
  }
  </code></pre>
  
  <p>UserDAO:</p>
  
  <p>@Repository
  public class UserDAO {</p>
  
  <pre><code>private JdbcTemplate jdbcTemplate;
  
  @Autowired
  public UserDAO(@Qualifier("dataSourceDB") DataSource dataSource) {
      this.jdbcTemplate = new JdbcTemplate(dataSource);
  }   
  
  // Various get and finder methods
  </code></pre>
  
  <p>}</p>
  
  <p>src/test/java:</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration(locations = "classpath:**/mvc-dispatcher-servlet.xml")
  @WebAppConfiguration
  public class UserControllerTest {
  
      @Autowired
      private WebApplicationContext ctx;
  
      private MockMvc mockMvc;
  
      @InjectMocks
      private UserController userController;
  
      @Before
      public void setUp() {
          MockitoAnnotations.initMocks(this);
          mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
      }
  
      @Test
      public void appUser() throws Exception {
          String appId = "1234FD57";
  
          mockMvc.perform(get("/v2/users/{appId}", appId)
                         .accept(MediaType.APPLICATION_JSON))
                         .andDo(print())
                         .andExpect(status().isOk());
      }
  }
  </code></pre>
  
  <p>Here's the output:</p>
  
  <pre><code>-------------------------------------------------------
   T E S T S
  -------------------------------------------------------
  Running com.myapp.rest.controllers.UserControllerTest
  
  MockHttpServletRequest:
           HTTP Method = GET
           Request URI = /v2/users/1234FD57
            Parameters = {}
               Headers = {Accept=[application/json]}
  
               Handler:
                  Type = com.myapp.rest.controllers.UserController
                Method = public java.lang.Object com.myapp.rest.controllers.UserController.getUserDetails(java.lang.String)
  
                 Async:
     Was async started = false
          Async result = null
  
    Resolved Exception:
                  Type = null
  
          ModelAndView:
             View name = null
                  View = null
                 Model = null
  
              FlashMap:
  
  MockHttpServletResponse:
                Status = 200
         Error message = null
               Headers = {}
          Content type = null
                  Body = 
         Forwarded URL = null
        Redirected URL = null
               Cookies = []
  Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.751 sec
  </code></pre>
  
  <p>The test runs but the body doesn't contain any JSON (notice how its blank)...</p>
  
  <p>When I change the contents of my test method to:</p>
  
  <pre><code>mockMvc.perform(get("/v2/users/{appId}",appId)
                     .accept(MediaType.APPLICATION_JSON))
                     .andExpect(status().isOk())
                     .andExpect(jsonPath("$[1].userId", is("1234FD57")));
  </code></pre>
  
  <p>Received the following error:</p>
  
  <pre><code>Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.766 sec &lt;&lt;&lt; FAILURE!
  
  user(com.myapp.rest.controllers.UserControllerTest)  Time elapsed: 0.157 sec  &lt;&lt;&lt; ERROR!
  org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.myapp.rest.controllers.UserControllerTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: 
  
  Could not autowire field: private com.myapp.rest.controllers.UserController 
      com.myapp.rest.controllers.UserControllerTest.userController; nested exception is org.springframework.beans.factory
      NoSuchBeanDefinitionException: No qualifying bean of type [com.myapp.rest.controllers.UserController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.mockito.InjectMocks(), @org.springframework.beans.factory.annotation.Autowired(required=true)}
      at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties
  </code></pre>
  
  <p>Its just like in the print() statement showing nothing for "Body" no JSON... Am getting really close, does anyone know what I am off by?</p>