2

我有 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() {
   ....
}

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

4

4 回答 4

3

怎么用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
  }

如果关闭,不知道为什么要格式化。

于 2012-10-25T17:35:45.700 回答
1

这是我将如何处理它:

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

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

这是主要的测试类:

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

于 2012-10-25T17:22:21.277 回答
1

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

  1. 创建一个包含测试的基类。
  2. 使用代表不同配置的基类扩展基类。
  3. 当您执行每个派生类时,基类中的测试将使用其自己类中的配置设置运行。
  4. 要添加新测试,您只需将它们添加到基类中。
于 2012-10-25T17:27:01.487 回答
0

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

于 2012-10-25T17:06:20.590 回答