JUnit:运行一个具有不同配置的测试

我有2种测试方法,我需要使用不同的配置运行它们

myTest() { ..... ..... } @Test myTest_c1() { setConf1(); myTest(); } @Test myTest_c2() { setConf2(); myTest(); } //------------------ nextTest() { ..... ..... } @Test nextTest_c1() { setConf1(); nextTest(); } @Test nextTest_c2() { setConf2(); nextTest(); } 

我不能从一个配置运行它们(如下面的代码),因为我需要单独的方法来执行tosca。

 @Test tests_c1() { setConf1(); myTest() nextTest(); } 

我不想写那两个方法来运行每个测试,我该如何解决这个问题?

首先我想写自定义注释

 @Test @RunWithBothConf myTest() { .... } 

但也许还有其他解决方案吗?

使用Theories怎么样?

 @RunWith(Theories.class) public class MyTest{ private static enum Configs{ C1, C2, C3; } @DataPoints public static Configs[] configValues = Configs.values(); private void doConfig(Configs config){ swich(config){...} } @Theory public void test1(Config config){ doConfig(config); // rest of test } @Theory public void test2(Config config){ doConfig(config); // rest of test } 

不确定为什么格式化关闭。

我在一堆测试用例中遇到了类似的问题,某些测试需要使用不同的配置运行。 现在,你的情况下的’配置’可能更像设置,在这种情况下,这可能不是最好的选择,但对我来说它更像是一个部署模型,所以它适合。

  1. 创建包含测试的基类。
  2. 使用表示不同配置的基类扩展基类。
  3. 在执行每个派生类时,基类中的测试将在其自己的类中使用配置设置运行。
  4. 要添加新测试,只需将它们添加到基类中即可。

以下是我将如何处理它:

  • 创建两个测试类
  • 第一个类配置为conf1但使用@Before属性触发设置
  • 第二个类扩展了第一个类但覆盖了configure方法

在下面的示例中,我有一个成员变量conf 。 如果没有运行配置,它将保持默认值0.setConf1现在是Conf1Test类中的Conf1Test ,它将此变量设置为1. setConf2现在是Conf2Test类中的Conf2Test

这是主要的测试类:

 public class Conf1Test { protected int conf = 0; @Before public void setConf() { conf = 1; } @Test public void myTest() { System.out.println("starting myTest; conf=" + conf); } @Test public void nextTest() { System.out.println("starting nextTest; conf=" + conf); } } 

第二个测试类

 public class Conf2Test extends Conf1Test { // override setConf to do "setConf2" function public void setConf() { conf = 2; } } 

当我配置我的IDE来运行包中的所有测试时,我得到以下输出:

 starting myTest; conf=1 starting nextTest; conf=1 starting myTest; conf=2 starting nextTest; conf=2 

我认为这会给你什么。 每个测试只需编写一次。 每个测试运行两次,一次使用conf1 ,一次使用conf2

你现在拥有它的方式对我来说似乎很好。 您没有复制任何代码,每个测试都清晰易懂。