【问题标题】:Spring Testing: How to enable auto-scan of beansSpring 测试:如何启用 bean 的自动扫描
【发布时间】:2014-06-18 10:37:54
【问题描述】:

例如,现在在每个测试课中我都要做

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)

我想摆脱

 @ContextConfiguration(loader=AnnotationConfigContextLoader.class)

并希望 Spring 扫描我项目中的所有 bean。

我该怎么做?

【问题讨论】:

    标签: spring unit-testing spring-test


    【解决方案1】:
        @TestConfiguration 
        @ComponentScan("basepackage")
        public class TestConfig{
    
        }
    

    添加一个配置类可以让 spring 加载应用程序上下文。 这为我解决了这个问题。

    【讨论】:

      【解决方案2】:

      如果使用 Spring Boot,您也可以简单地添加 @SpringBootTest

      【讨论】:

      • 不知道为什么这被否决了。添加它完全避免了使用@ContextConfiguration。
      • 感谢您的有用评论!我以为是因为 OP 没有提到 Spring Boot,所以我有点束手无策。
      • 这对我不起作用,它会导致新的错误消息。
      【解决方案3】:

      你可以这样做:

      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration
      public class MyTest {
      
        @Test
        public void testSomething() {
      
        }
      
        @Configuration
        @ComponentScan("basepackage")
        public static class SpringConfig {
      
        }
      }
      

      默认情况下,@ContextConfiguration 将查找带有 @Configuration 注释的静态内部类,这就是为什么这个设置可以正常工作的原因。

      您可以完全摆脱 loader 参数,这不是必需的

      【讨论】:

      • 如果我在测试中的方法上使用@Before 注释会怎样?该方法实际上会在@Configuration 之前执行吗?
      • 这是在我的情况下试图寻找 xml Caused by: java.io.FileNotFoundException: class path resource [mypackage/MyTest-context.xml] cannot be opened because it does not exist
      • 我更喜欢在“集成”测试中使用此注释来启动 WEB 应用程序。通过这种方式,测试执行得更快。
      【解决方案4】:

      如果你在一个 xml 文件中有你的 spring 配置,你会使用类似的东西:

      @ContextConfiguration(locations="classpath:applicationContext.xml")
      

      如果您使用 Java Config,那么您将使用

      @ContextConfiguration(classes=Config.class)
      

      我在上面的示例中使用了通用名称,您当然需要适应您的项目配置。

      在这两种情况下,都需要启用 Spring 的组件扫描,以便 Spring 拾取带注释的类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        相关资源
        最近更新 更多