【发布时间】:2013-04-14 17:18:45
【问题描述】:
我正在尝试使用 Spring 3.2.1 创建 spring-mvc 测试。按照一些教程,我认为这将是直截了当的。
这是我的测试:
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = { JpaTestConfig.class } )
@WebAppConfiguration
public class HomeControllerTest {
@Resource
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Test
public void testRoot() throws Exception {
mockMvc.perform(get("/").accept(MediaType.TEXT_PLAIN)).andDo(print())
// print the request/response in the console
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.TEXT_PLAIN))
.andExpect(content().string("Hello World!"));
}
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
}
这是我相关的 pom.xml:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
我有以下测试配置类:
@Configuration
@EnableTransactionManagement
@ComponentScan( basePackages = { "com.myproject.service", "com.myproject.utility",
"com.myproject.controller" } )
@ImportResource( "classpath:applicationContext.xml" )
public class JpaTestConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
...
}
// various other services/datasource but not controllers
}
据我了解,添加 @WebAppConfiguration 将强制 Spring 注入它。但是当我在 Eclipse 中运行这个测试时,我得到:
原因: org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 符合条件的 bean 类型 [org.springframework.web.context.WebApplicationContext] 找到 依赖项:预计至少有 1 个符合自动装配条件的 bean 这种依赖的候选人。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:967) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:837) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:749) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
更新 - 我必须更改我的测试 Java 配置类
@Configuration
@EnableWebMvc
@ComponentScan( basePackages = { "...." } )
@EnableTransactionManagement
@ImportResource( "classpath:applicationContext.xml" )
public class JpaTestConfig extends WebMvcConfigurationSupport {
但是,现在的问题是我可以调用我的 REST 服务,但它正在调用其他一些服务,包括数据库调用。仅测试呼叫和模拟响应的首选方法是什么。我想测试有效和无效条件。
【问题讨论】:
标签: unit-testing spring-mvc spring-mvc-test