【发布时间】:2014-07-02 22:26:26
【问题描述】:
背景
我正在尝试在 Spring 中实现控制器的集成测试。我不想使用 WebApplicationInitializer(Spring 的 Java 配置)来运行我的 Web 应用程序。我想使用基于 xml 的配置。但是@ContextConfiguration无法加载web.xml,所以我创建了application-context.xml。问题是web.xml 和application-context.xml 的目的是一样的,
问题
我可以删除web.xml 以支持application-context.xml 吗?如果我删除 web.xml,测试会通过,但 Web 应用程序不会在 Tomcat 中运行。
代码
这是我的测试课:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:path/to/application-context.xml"})
@WebAppConfiguration
public class HelloControllerIntegrationTest {
@Autowired
private WebApplicationContext context;
private WebClient webClient;
@Before
public void setup() throws Exception {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
webClient = new WebClient();
webClient.setWebConnection(new MockMvcWebConnection(mockMvc));
}
@Test
public void testPrintWelcome() throws Exception {
// I'm trying to print out the page for now
UnexpectedPage welcomePage = webClient.getPage("http://localhost/");
InputStream is = welcomePage.getInputStream();
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
String a = s.hasNext() ? s.next() : "";
System.out.println(a);
}
}
这是我的application-context.xml
<?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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.company.controller"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
</bean>
</beans>
【问题讨论】:
-
您的测试代码是否通过? Spring MVC 测试与你是否使用 web.xml 来初始化应用程序无关,因为它永远不会在 servlet 容器中启动应用程序。
-
@geo 是的,所有测试都通过了。没有抛出异常。
标签: java spring-mvc tomcat7 integration-testing web.xml