@WebAppConfiguration没有注入

时间:2013-04-21 21:24:15

标签: unit-testing spring-mvc spring-mvc-test

我正在尝试使用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有资格成为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}     在   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服务,但它正在调用其他一些服务,包括数据库调用。仅测试呼叫和模拟响应的首选方法是什么。我想测试有效和无效的条件。

4 个答案:

答案 0 :(得分:22)

在我的案例中,问题已经通过替换:

解决了
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { ... })

@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { ... })

注意加载器类名中的 Web 。使用上一个加载器,尽管GenericApplicationContext注释已注入@WebAppConfiguration

答案 1 :(得分:5)

以下设置仅使用Java配置类,对我来说效果很好。

@WebAppConfiguration
@ContextConfiguration(classes = TestApplicationContext.class)
public class MyClassTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setUp() {
        mockMvc = webAppContextSetup(wac).build();
    }
    ....       
}

@Configuration
public class TestApplicationContext {

    @Bean
    public MyBean myBeanId(){
        return Mockito.mock(MyBean.class);
    }
    ....
}

在测试类上仅存在@WebAppConfiguration可确保使用指向Web应用程序根目录的默认路径为测试加载WebApplicationContext。因此,您可以自动装配WebApplicationContext并使用它来设置mockMvc。

请注意,@ WebAppConfiguration必须与测试类中的@ContextConfiguration结合使用。

答案 2 :(得分:0)

为什么不添加此注释并查看它是否有效。将XXXX-text.xml替换为bean映射xml。

@ContextConfiguration(locations={"classpath:/XXXX-test.xml"})

答案 3 :(得分:0)

其中一项测试可用于带有注释标头的本地开发人员支持,在那里我遇到了与问题类似的问题。

评论是该测试的先前版本。

@RunWith(SpringJUnit4ClassRunner.class)
/* @EnableJpaAuditing */ /* for jpa dates */ /* it should be defined only once, 
because 'jpaAuditingHandler' defined in null on application startup */
@EntityScan(basePackageClasses = { EnableJpaAuditing.class, Jsr310JpaConverters.class })
//@ProfileValueSourceConfiguration(Application.class)
//@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class)
//@PropertySource("classpath:application.properties")
@TestPropertySource(locations = "classpath:application.properties")
//@WebAppConfiguration
@SpringBootTest
public class JpaTests {/* */}
相关问题