MockMvc to test SpringMVC Rest Web Service using J

2019-08-09 04:49发布

问题:

Am using Spring MVC to create Restful Web Services...

Here's my pom.xml:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.0.3.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.0.3.RELEASE</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.0.3.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.0.3.RELEASE</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.10.19</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path-assert</artifactId>
    <version>0.9.1</version>
    <scope>test</scope>
</dependency>

WEB-INF/web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <display-name>MyApp</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>

        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>
</web-app>

WEB-INF/mvc-dispatcher-servlet.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    <import resource="classpath:database_db.xml" />

    <context:component-scan base-package="com.myapp.rest" />
    <mvc:annotation-driven />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

src/main/resources/database_db.xml:

<beans xmlns="http://www.springframework.org/schema/beans">
    <bean id="dataSourceDB"  class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
        <property name="url"><value>jdbc:mysql://localhost/mydatabase?zeroDateTimeBehavior=convertToNull</value></property>
        <property name="username"><value>root</value></property>
        <property name="password"><value></value></property>
    </bean> 
</beans>

UserController:

@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;
    }
}

UserDAO:

@Repository public class UserDAO {

private JdbcTemplate jdbcTemplate;

@Autowired
public UserDAO(@Qualifier("dataSourceDB") DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}   

// Various get and finder methods

}

src/test/java:

@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());
    }
}

Here's the output:

-------------------------------------------------------
 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

The test runs but the body doesn't contain any JSON (notice how its blank)...

When I change the contents of my test method to:

mockMvc.perform(get("/v2/users/{appId}",appId)
                   .accept(MediaType.APPLICATION_JSON))
                   .andExpect(status().isOk())
                   .andExpect(jsonPath("$[1].userId", is("1234FD57")));

Received the following error:

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.766 sec <<< FAILURE!

user(com.myapp.rest.controllers.UserControllerTest)  Time elapsed: 0.157 sec  <<< 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

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?

回答1:

Since you are working with Spring 4.0.3 you have to use the old jsonpath 0.9.1, see https://jira.spring.io/browse/SPR-12299



回答2:

I don't think you are initialising your UserController in your test. You can either:

  1. Initialise it in the test yourself. UserController userController = new UserController();
  2. @Autowire the UserController. But you would also need to include the configuration with your component scan into the @ContextConfiguration