我已经构建了一个有效的Spring MVC Web应用程序,利用Hibernate和JPA,只有一个端点,只有在通过Web浏览器调用时才能成功返回JSON。
我还对类进行了单元测试,特别是映射终点的主控制器。
所以我的下一步是使用spring MVC测试框架编写一些行为测试来测试JSON端点及其所有工作部分(配置,控制器,服务,模型和存储库)。
我已成功设置了一个使用我的应用程序配置的测试,将一起注入/自动装配,然后针对我的终点发出'GET'请求。我可以通过调试控制器端点,通过服务,到存储库,成功获取数据并返回正确的模型对象来调试调用。但是,控制器然后返回406未接受的响应,并且测试失败。
我花了两天的时间来完成这个问题,并且已经阅读了几篇关于每篇博文的回复以及我可以采取的回答,没有任何建议。
这是我的控制器:
@Controller
public class DataController {
@Autowired
private IService service;
@RequestMapping(
value = "/data",
method = RequestMethod.GET,
produces = "application/json"
)
public @ResponseBody
ModelData getDataByCode(@RequestParam String code) {
return service.getDataCode(code);
}
}
服务:
@Service("dataService")
public class DataService implements IService {
@Autowired
private IDataRepository dataRepository;
@Transactional
public ModelData getDataByCode(String code){
return dataRepository.getDataByCode(code);
}
}
存储库:
@Repository("dataRepository")
public class DataRepository implements IDataRepository {
@PersistenceContext
private EntityManager entityManager;
public ModelData getDataByCode(String code) throws IllegalStateException, PersistenceException {
String selectJPAQueryBase = "Select data from ModelData data where data.code = %s";
Query query = entityManager.createQuery(String.format(selectJPAQueryBase, code));
return (ModelData) query.getSingleResult();
}
}
与核心功能相关的依赖关系:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.14.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>3.2.14.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.14.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.14.RELEASE</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.4</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.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.14.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
JPA上下文:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config />
<!-- where spring will start to look for classes that are annotated, allow this to find all annotated classes -->
<context:component-scan base-package="com.app"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.SQLServer2008Dialect"/>
<entry key="hibernate.hbm2ddl.auto" value="validate"/>
<entry key="hibernate.format_sql" value="true"/>
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="url" value="jdbc:jtds:sqlserver://0.0.0.0:1433/dbname"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</bean>
</beans>
Web.xml中:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/jpaContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dataByCode</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dataByCode</servlet-name>
<url-pattern>/data</url-pattern>
</servlet-mapping>
</web-app>
Servlet配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- allows POJO objects to just use annotations for simply hooking into spring framework -->
<mvc:annotation-driven/>
<!-- where spring will start to look annotated classes, keep this to controller level -->
<context:component-scan base-package="com.app"/>
<!-- load properties files and similar -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="properties"/>
</bean>
<!-- basic resolver to handle jsp pages, usually linked to returning html -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="order" value="2"/>
</bean>
</beans>
失败的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:jpaContext.xml")
public class GetDataCodeIntTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
@Test
public void getDataByCode() throws Exception {
String code = "1234";
this.mockMvc.perform(MockMvcRequestBuilders.get("/data").param("code", code))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value(code));
}
}
这里的关键是应用程序通过浏览器完美运行,但在控制器返回响应时无法使用spring mvc测试框架。
更新:
解决方案是将我的servlet-config.xml和jpaContext一起注入@ContextConfiguration
,之后测试运行完美。
有趣的是,我不能只从类路径加载servlet-config.xml,但我并不想要维护一个特定于测试的版本,所以我把它移到了我的资源文件夹中。这是不是一个好主意我还没有决定,但它现在从类路径开始工作。
答案 0 :(得分:1)
尝试将servletConfig.xml
添加到测试类的@ContextConfiguration
:
@ContextConfiguration({"classpath:jpaContext.xml", "classpath:path/to/servlet-context.xml"})
其中重要的一点是<mvc:annotation-driven/>
。
另请注意,您可以稍微简化控制器,并通过对其@RestController
而不是@Controller
进行注释来使其目的更加清晰。
答案 1 :(得分:1)
尝试通过@ContextConfiguration添加spring-context.xml进行测试(例如:@ContextConfiguration(&#34; classpath:spring-context.xml&#34;)),用这个选项尝试你的代码,它有效。
答案 2 :(得分:0)
我认为您的问题是您误解了“内容类型”标题,结果由您的REST控制器生成。
事实上,你把
MockMvcResultMatchers.content()。contentType中(MediaType.APPLICATION_JSON)
表示您正在向控制器发送JSON。 然而,您的控制器试图在您的请求中接收参数而不是JSON:
@RequestParam字符串代码
可能是您拥有此406的原因(通常表示您的请求标题中的默认值)。