本文介绍了阻止在JUnit测试期间执行Application/CommandLineRunner类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在您的TestCase类中有以下注释:

If in your TestCase class there is this annotations:

@SpringApplicationConfiguration(classes = {Application.class})

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

this will cause the Application.class, implementing the CommandLineRunner interface, to run the required method

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

我仍然认为这在大多数情况下是不想要的行为,因为在您的测试环境中,您可能不想启动整个应用程序.

I still think this is, mostly, a not wanted behaviour, since in your test environment you may not want to launch the entire application.

我有两种解决该问题的方法:

I have in mind two solution to circumvent this problem:

  1. 从我的Application类中删除CommandLineRunner接口
  2. 具有不同的测试环境
  1. to remove the CommandLineRunner interface from my Application class
  2. to have a different context for testing

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

Both this solution requires lot of coding.Do you have a more convenient solution?

推荐答案

Jan的解决方案可以更轻松地实现.

Jan's solution can be achieved easier.

在您的测试课程中,激活测试"配置文件:

In your test class, activate the "test" profile:

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

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

In your CommandLineRunner set the profile to NOT test:

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

然后,您不必在应用程序中手动设置配置文件.

Then you don't have to manually set the profile in the Application.

这篇关于阻止在JUnit测试期间执行Application/CommandLineRunner类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:14