【问题标题】:@WebAppConfiguration not injected@WebAppConfiguration 未注入
【发布时间】: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


    【解决方案1】:

    在我的情况下,问题已通过替换解决:

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

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

    注意加载器类名中的Web。在之前的加载器中,GenericApplicationContext 已被注入,尽管有 @WebAppConfiguration 注释。

    【讨论】:

    • 太棒了!我正在使用 Spring 4.2 并进行了很多搜索来解决这个问题。还添加了@WebAppConfiguration,但它不起作用。这解决了我的问题。
    • 这正是解决我问题的正确方法!作为替代方案,我简单地从“@ContextConfiguration”中删除了“加载器”,这样 AnnotationConfigContextLoader 就不会与“@WebAppConfiguration”发生冲突
    【解决方案2】:

    以下设置仅使用 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 一起使用。

    【讨论】:

      【解决方案3】:

      你为什么不添加这个注释,看看它是否有效。将 XXXX-text.xml 替换为您的 bean 映射 xml。

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

      【讨论】:

      • 我的 bean 映射到 @Configuration:
      • 原来我需要在我的测试配置类中添加以下内容:@EnableWebMvc @ComponentScan(...) JpaTestConfig extends WebMvcConfigurationSupport
      • 很好的发现。将此更新添加到您的问题中。或者尝试详细回答您的问题。
      • 谢谢 Java_Dude,我更新了,但现在我遇到了 REST 服务抛出异常的问题。有没有办法注入模拟服务,这样它们就不会爆炸?
      • 什么错误?这可能是因为依赖?你在lib中有orm jar吗?您可以发布一些代码吗?...如果您开始另一个问题并提供链接,那就太好了。我很乐意为您提供帮助。
      【解决方案4】:

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

      cmets 是此测试的先前版本。

      @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 {/* */}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-02
        • 2013-10-01
        • 2018-10-28
        • 1970-01-01
        • 1970-01-01
        • 2016-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多