使用MockMvc、Test -context.xml和基于注释的WebAppConfig(即Java)进行Spring



版本(SpringBoot isnot)涉及):

Spring: 5.2.16
web-app / servlet API: 4.0
JUnit: 5.8

Spring MVC测试不适用于返回ResponseEntity<ReturnStatus>的控制器端点,其中ReturnStatus是具有适当getter/setter的POJO。触发异常说明ReturnStatus无法进行JSON转换。我的研究表明,没有加载WebApplicationContext的基于注释的Java配置(因此无法识别Jackson JSON转换器)。奇怪的是,在Tomcat中的非测试部署中,控制器端点工作得很好,可能是因为Tomcat解析了war文件中的web.xml

问题:
我如何调整这个应用程序的Spring MVC测试设置,以便正确加载WebApplicationContext的基于注释的Java配置?例如,这可以在端点测试逻辑(即JUnit测试)中显式地完成吗?

异常:

14:33:57,765  WARN DefaultHandlerExceptionResolver:199 - Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class com.acme.myapp.io.ReturnStatus] with preset Content-Type 'null']
14:33:57,765 DEBUG TestDispatcherServlet:1131 - Completed 500 INTERNAL_SERVER_ERROR

Spring MVC应用程序包含以下配置:

  1. test-context.xml,包含访问数据存储的Spring bean配置:
  2. web.xml,声明并映射DispatcherServlet与WebApplicationContext的相关设置。
  3. 基于注释的配置在WebMvcConfigurer的Java实现中。

节选自test-context.xml:

<context:component-scan base-package="com.acme.myapp"/>
<jpa:repositories base-package="com.acme.myapp.repos"/>
<context:property-placeholder location="classpath:/application.properties" />
<!-- Data persistence configuration -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${db.showSql}" />
<property name="databasePlatform" value="${db.dialect}" />
<property name="generateDdl" value="${db.generateDdl}" />
</bean>
</property>
<property name="packagesToScan">
<list>
<value>com.acme.myapp.dao</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.user}" />
<property name="password" value="${db.pass}" />
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
<property name="accessToUnderlyingConnectionAllowed" value="true"/>
</bean>
<!-- Set JVM system properties here. We do this principally for hibernate logging. -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.System" />
<property name="targetMethod" value="getProperties" />
</bean>
</property>
<property name="targetMethod" value="putAll" />
<property name="arguments">
<util:properties>
<prop key="org.jboss.logging.provider">slf4j</prop>
</util:properties>
</property>
</bean>

web.xml的相关节选(其中application-context.xmltest-context.xml的生产版本):

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>central-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.acme.myapp.MyAppWebAppConfig</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>central-dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>

摘自WebMvcConfigurer的Java实现(即,我们合并了Jackson JSON转换器):

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.acme.myapp.controllers" })
public class MyAppWebAppConfig implements WebMvcConfigurer
{
private static final Logger logger = LoggerFactory.getLogger(MyAppWebAppConfig.class);
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters)
{
logger.debug("extendMessageConverters ...");
converters.add(new StringHttpMessageConverter());
converters.add(new MappingJackson2HttpMessageConverter(new MyAppObjectMapper()));
}
}

控制器端点看起来像这样(根在/patients):

@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ReturnStatus> readPatient(
@PathVariable("id") long id
)
{
ReturnStatus returnStatus = new ReturnStatus();
returnStatus.setVersionId("1.0");
...
return new ResponseEntity<ReturnStatus>(returnStatus, httpStatus);
}

使用JUnit5和MockMvc,端点测试看起来像这样:

@SpringJUnitWebConfig(locations={"classpath:test-context.xml"})
public class PatientControllerTest
{
private MockMvc mockMvc;
@BeforeEach
public void setup(WebApplicationContext wac) {
this.mockMvc = webAppContextSetup(wac).build();
}
@Test
@DisplayName("Read Patient from /patients API.")
public void testReadPatient()
{
try {
mockMvc.perform(get("/patients/1").accept(MediaType.APPLICATION_JSON_VALUE))
.andDo(print())
.andExpect(status().isOk());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

谢谢!

这里有一些选项,可能不是详尽的:

  • 根据前面的评论,我们可以简单地在test-context.xml中使用<mvc:annotation-driven>指令。例如:
<bean id="myappObjectMapper" class="com.acme.myapp.MyAppObjectMapper"/>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<constructor-arg ref="myappObjectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

这个指令有效地避免了加载MyAppWebAppConfig的需要,因为<mvc:annotation-driven>实际上是Java中注释@EnableWebMvc的xml等价物。

  • 实现WebApplicationInitializer,以便在Java中有效地执行我们配置到web.xml中的内容。例如:
public class MyAppWebApplicationInitializer implements WebApplicationInitializer
{
@Override
public void onStartup(ServletContext container)
{
XmlWebApplicationContext appCtx = new XmlWebApplicationContext();
appCtx.setConfigLocation("classpath:application-context.xml");
container.addListener(new ContextLoaderListener(appCtx));
AnnotationConfigWebApplicationContext dispatcherCtx = new AnnotationConfigWebApplicationContext();
dispatcherCtx.register(MyAppWebAppConfig.class);
ServletRegistration.Dynamic registration = container.addServlet("central-dispatcher", new DispatcherServlet(dispatcherCtx));
registration.setLoadOnStartup(1);
registration.addMapping("/api/*");
}  
}

对于这个方案,我们从项目中删除web.xml;可能我们也应该把application-context.xml的引用参数化。

请注意,当我运行JUnit5测试时,Spring似乎没有实例化MyAppWebApplicationInitializer,相反,为JUnit5加载的Spring上下文是@SpringJUnitWebConfig注释引用的上下文。因此,我建议将与测试相关的配置与test-context.xml放在一起,并为生产保留WebApplicationInitializer

我相信还有其他的选择,但我只探讨了这两种方法。

最新更新