【问题标题】:Prevent method from running when using @EventListener(ApplicationReadyEvent.class) during testing在测试期间使用 @EventListener(ApplicationReadyEvent.class) 时阻止方法运行
【发布时间】:2020-01-11 15:17:17
【问题描述】:

我的项目中有以下测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class AddressParserTest {

    @Test
    public void parseAddressTest() {
        try {
          // my code
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

我的项目中有一些方法用 @EventListener(ApplicationReadyEvent.class) 注释,在 Spring Boot 启动后运行

@Component
public class MyClass {

    @EventListener(ApplicationReadyEvent.class)
    public void myMethod() {
       //my code
    }
}

当我运行 AddressParserTest 时,myMethod 方法也会运行,因为 @EventListener(ApplicationReadyEvent.class) 是否有任何方法阻止它在测试期间运行?

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

    您可以在这种情况下使用配置文件。

    • @Profile注释你的类(请注意“test”前面的“!”。这意味着:加载这个类,只有当配置文件不是“test”时)
    @Component
    @Profile("!test")
    public class MyClass {
    
        @EventListener(ApplicationReadyEvent.class)
        public void myMethod() {
           //my code
        }
    }
    
    • @ActiveProfiles("test")注释你的测试类
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @ActiveProfiles("test")
    public class AddressParserTest {
    
        @Test
        public void parseAddressTest() {
            try {
              // my code
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 2023-02-07
      • 1970-01-01
      相关资源
      最近更新 更多