如何在另一个测试类中使用现有的 JUnit 测试,使其通过@before?



我知道这个论坛中还有另一个问题似乎相似。请在标记重复之前阅读。

我正在寻找一种运行测试的方法,该测试是在另一类中定义的,它将通过@beforefore。

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((时 - 您将不会在 @be之前进行TestClass1的注释,在我的情况下,这是为了启动其他对象。

也许还有另一种方式?

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

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

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

将您想要的代码放入before()方法中,然后将JUnit Rule定义为:

@Rule
public ExternalResource resource = new SetupResource ()

假设同一类的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{} 

最新更新