gpt4 book ai didi

spring - 防止 Application/CommandLineRunner 类在 JUnit 测试期间执行

转载 作者:IT老高 更新时间:2023-10-28 13:03:26 25 4
gpt4 key购买 nike

如果在您的 TestCase 类中有这样的注释:

@SpringApplicationConfiguration(classes = {Application.class})

这将导致实现 CommandLineRunner 接口(interface)的 Application.class 运行所需的方法

public void run(String... args) throws Exception

我仍然认为这主要是不想要的行为,因为在您的测试环境中,您可能不想启动整个应用程序。

我想到了两个解决这个问题的方法:

  1. 从我的 Application 类中删除 CommandLineRunner 接口(interface)
  2. 拥有不同的测试环境

这两种解决方案都需要大量编码。你有更方便的解决方案吗?

最佳答案

Jan 的解决方案可以更容易实现。

在您的测试类中,激活“测试”配置文件:

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
public class MyFancyTest {}

在您的 CommandLineRunner 中将配置文件设置为不测试:

@Component
@Profile("!test")
public class JobCommandLineRunner implements CommandLineRunner {}

那么您不必在应用程序中手动设置配置文件。

关于spring - 防止 Application/CommandLineRunner 类在 JUnit 测试期间执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29344313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com