Mockito和Hamcrest测试SpringMVC

Mockito和Hamcrest测试SpringMVC

本文介绍了MockMvc使用JUnit,Mockito和Hamcrest测试SpringMVC Rest Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring MVC创建Restful Web服务...

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

这是我的pom.xml:

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:

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:

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:

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:

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:

@存储库公共类UserDAO {

@Repositorypublic 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:

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

这是输出:

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

运行测试,但是主体不包含任何JSON(请注意其空白)...

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")));

收到以下错误:

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

就像在print()语句中什么都没有显示"Body"一样,没有JSON ...越来越接近了,有人知道我的遭遇吗?

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?

推荐答案

我不认为您正在测试中初始化UserController.您可以:

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

  1. 在测试中自行初始化. UserController userController = new UserController();
  2. @自动连线UserController.但是您还需要将配置和组件扫描一起包含到@ContextConfiguration
  3. 中.
  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

这篇关于MockMvc使用JUnit,Mockito和Hamcrest测试SpringMVC Rest Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:43