【问题标题】:How to use an existing JUnit test in another test class, in a way that it'll go through @before?如何以通过@before 的方式在另一个测试类中使用现有的JUnit 测试?
【发布时间】:2017-06-25 14:05:39
【问题描述】:

我知道这个论坛中还有一个问题可能看起来很相似。请在标记为重复之前通读。

我正在寻找一种方法来运行测试,该测试在另一个类中定义,它会通过 @before 注释。

public TestClass1 {
    @before
    public void setup() throws Exception{
        super.setup();
    }

    @Test
    public void testSomething(){...}
}

public TestClass2 {
    @Test
    public void testSomethingAndSomethingElse() {
       // Somehow execute testSomething() in a way which will force 
          it to go through the @before
       // and then test something else
       }
}

在类似的在线问题中,有 2 条建议:
1. 从 TestClass1 扩展 TestClass2 - 这对我来说是不可能的,因为我已经扩展了另一个类。
2. 使用委托从 TestClass2 访问 TestClass1,如下所示:

// Instantiate TestClass1 as a member of TestClass2
public TestClass2 {
    private TestClass1 one = new TestClass1();
    public void testSomethingAndSomethingElse1() {
        one.testSomething();
    }
}

这里的问题是,当调用 one.testSomething() 时 - 您不会通过 TestClass1 的 @before 注释,在我的情况下,它是初始化其他对象所必需的。

也许还有其他方法?

用于集成测试而不是单元测试。 我需要能够在另一个 @test 中使用 @test,而不是任何其他解决方法。

【问题讨论】:

  • TestClass2 显式调用setup() 怎么样?
  • 因为 setup() 正在为 TestClass1 中的 @test 准备数据。从 TestClass2 调用时,此数据将超出 TestClass1 的范围。
  • TestClass1TestClass2 是同一类的子类吗?如果是这样,请考虑将 @before 注释移至其超类。
  • 是的,它们是同一类的子类。我会试试的。

标签: java junit automation integration-testing


【解决方案1】:

如果您尝试在许多测试类中重用相同的代码,我建议使用来自JUnit 框架的@Rule。也许ExternalResource 是你需要的:

public class SetupResource extends ExternalResource {
    @Override
      protected void before() throws Throwable {
       //setup the code
    }
}

把你想要的代码放在before()方法中,然后像这样定义JUnitRule

@Rule
public ExternalResource resource = new SetupResource ()

【讨论】:

    【解决方案2】:

    假设同一类的TestClass1TestClass2 子类考虑将@before 注释拉到它们的超类:

    public class TestCalss {
    
        @Before
        public void setUp() throws Exception {
            System.out.println("setup");
        }
    }
    
    public class TestCalss1 extends TestCalss{}
    public class TestCalss2 extends TestCalss{} 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-23
      • 2021-12-27
      • 2011-01-30
      • 1970-01-01
      • 2018-04-12
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多