gpt4 book ai didi

json - Spring MVC 测试框架 - JSON 端点仅在测试中返回 406

转载 作者:行者123 更新时间:2023-12-04 16:48:19 25 4
gpt4 key购买 nike

我已经使用 Hibernate 和 JPA 构建了一个工作的 Spring MVC web 应用程序,它有一个端点,只有在通过 web 浏览器调用时才会成功返回 JSON。

我还通过了针对类的单元测试,尤其是映射端点的主 Controller 。

所以我的下一步是使用 spring MVC 测试框架编写一些行为测试,以测试 JSON 端点及其所有工作部分(配置、 Controller 、服务、模型和存储库)。

我已经成功地设置了一个测试,该测试使用我的应用程序配置,将事物注入(inject)/自动连接在一起,然后针对我的端点发出“GET”请求。我可以调试调用,跟踪从到达 Controller 端点、通过服务到存储库、成功获取数据并返回正确的模型对象的过程。但是, Controller 随后返回 406 未接受响应,测试失败。

我花了 2 天的时间来解决这个问题,并且几乎阅读了每篇博客文章和我可以接受的答案,没有任何建议有效。

这是我的 Controller :

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

网络.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));
}

}

这里的关键是应用程序通过浏览器完美运行,但在 Controller 返回响应时使用 spring mvc 测试框架失败。


更新:

解决方案是将我的 servlet-config.xml 与 jpaContext 一起注入(inject)到 @ContextConfiguration 中,之后测试运行完美。

有趣的是,我不能只从类路径加载 servlet-config.xml,而且我不想维护特定于测试的版本,所以我将它移到了我的资源文件夹中。我不确定这是否是个好主意,但它现在可以在类路径中使用。

最佳答案

尝试添加您的 servletConfig.xml@ContextConfiguration在你的测试课上:

@ContextConfiguration({"classpath:jpaContext.xml", "classpath:path/to/servlet-context.xml"})

其中重要的一点是 <mvc:annotation-driven/> .

另请注意,您可以通过注释 @RestController 稍微简化您的 Controller ,并使其用途更清晰。而不是 @Controller .

关于json - Spring MVC 测试框架 - JSON 端点仅在测试中返回 406,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34131220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com