有一个代码库,该代码库使用SpringMVC 4.0.3.Release用于RESTFUL WEB服务。
CodeBase包含一个功能齐全的RESTFUL Web服务,我可以使用Postman和Curl验证作品。
但是,当尝试使用MockMVC编写特定的REST FERFER服务的单元测试时,我被试图从单元测试中获取JSON内容的阻塞。
想知道它是一个配置问题还是我没有正确创建假对象的问题(因为这不依赖于tomcat,并且是独立的(。
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-webmvc</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>
<!-- A bunch of other Spring libs omitted from this post -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</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>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-assert</artifactId>
<version>0.9.1</version>
<scope>test</scope>
</dependency>
webconfig:
package com.myapp.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@EnableWebMvc
@Configuration
@ComponentScan("com.myapp.rest")
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
}
servetinitializer:
package com.myapp.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.myapp.config.WebConfig;
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
}
usercontroller:
@RestController
@RequestMapping("/v2")
public class UserController {
private final UserDAO dao;
private HttpHeaders headers = null;
@Autowired
public UserController(UserDAO dao) {
this.dao = dao;
headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
}
@RequestMapping(value = "users/{appId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public ResponseEntity<Object> getUserDetails(@PathVariable String appId) {
Object jsonPayload = dao.getUser(appId);
return new ResponseEntity<Object>(jsonPayload, headers, HttpStatus.OK);
}
}
用户多:
@Repository
public class UserDAO {
private JdbcTemplate jdbcTemplate;
@Autowired
public UserDAO(@Qualifier("dataSourceDB") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
// Finders methods (such as the getUser(appId)) which use Spring JDBC
}
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.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.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>${jdbc.driver}</value></property>
<property name="url"><value>${db.url}</value></property>
<property name="username"><value>${db.username}</value></property>
<property name="password"><value>${db.password}</value></property>
</bean>
</beans>
我的实际单位测试: 软件包com.myapp.rest.controllers;
RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:**/mvc-dispatcher-servlet.xml")
@WebAppConfiguration
public class UserControllerTest {
private MockMvc mockMvc;
@Mock
private UserDAO dao;
@InjectMocks
private UserController controller;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void getUserDetails() throws Exception {
String appId = "23bdr4560l";
mockMvc.perform(get("/v2/users/{appId}",appId)
.accept(MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
}
}
当我在本地调用我的构建时:
mvn clean install
生成的输出到stdout:
运行com.myapp.rest.controllers.usercontrollertest
MockHttpServletRequest:
HTTP Method = GET
Request URI = /v2/users/23bdr4560l
Parameters = {}
Headers = {Accept=[application/json]}
Handler:
Type = com.myapp.rest.controllers.UserController
Method = public org.springframework.http.ResponseEntity<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=[application/json]}
Content type = application/json
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.728 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
注意JSON主体部分是空的/null:
Body =
所以,尝试使用JSONPATH访问JSON有效载荷时:
@Test
public void getUserDetails() throws Exception {
String appId = "23bdr4560l";
mockMvc.perform(get("/v2/users/{appId}",appId)
.accept(MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andDo(print());
}
收到以下错误:
Results :
Tests in error:
getUserDetails(com.myapp.rest.controllers.UserControllerTest): json can not be null or empty
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
我可能会做什么错?
显然,我需要嘲笑响应,但已经搜索了这一点,而其他使用MockMVC的其他响应则能够获得JSON的测试。
这是一个配置问题(我需要为我的单位测试提供某种类型的注释(?
做,我需要在测试中实例化控制器?
奇怪的是,实际的休息调用有效(返回有效的JSON(,并使用邮递员和卷发...
此代码库没有@Service类/层,它的只是@RestController与@repository交谈(请参见上文(。
真的认为对基于Spring MVC的RESTFUL Web服务的测试支持会容易得多。
想法用完了...
任何帮助我最感激...
当您尝试像这样模拟bean时,它会尝试使用默认构造函数创建模拟。
@Mock
private UserDAO dao
它在实际休息呼叫的情况下起作用,因为您在运行时提供依赖的DataSource dataSource
。为UserDAO
类提供有效的依赖模拟。
,由于您要模拟用户Dao,因此需要对呼叫提供一些模拟期望:
Object jsonPayload = dao.getUser(appId);
在您的控制器内部,默认情况下它将返回null。要执行此操作,请在MockMVC调用之前使用测试中的Mockito.when((方法:
when(dao.getUser(anyString())).thenReturn(json)
json是您自己设置的一些硬编码的JSON对象。
对于初学者,由于您使用的是MockMvcBuilders.standaloneSetup(...)
,因此实际上您没有使用 Spring testContext Framework (TCF(加载WebApplicationContext
。因此,只需在您的测试类中完全删除以下声明:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:**/mvc-dispatcher-servlet.xml")
@WebAppConfiguration
另外,您可以完全忽略XML配置文件,因为没有WebApplicationContext
。
顺便说一句,TCF从未使用web.xml
和Servlet初始化器,因此您也可以忽略它们。
然后,如@plog所述,您需要设置对模拟UserDAO
的期望;否则,dao.getUser(appId)
的调用始终返回null
,这会导致一个空的响应主体。
问:
SAM(春季TestContext Framework的作者(