JUNIT:对于大量测试类只运行一次安装

neo*_*ite 21 java database junit unit-testing package

我有一个课程,我用它作为单元测试的基础.在这个类中,我初始化我的测试的整个环境,设置数据库映射,在多个表中输入许多数据库记录等.该类有一个带有@BeforeClass注释的方法来进行初始化.接下来,我将该类扩展为具有@Test方法的特定类.

我的问题是,由于前一类对于所有这些测试类完全相同,我如何确保它们仅对所有测试运行一次. 一个简单的解决方案是我可以将所有测试保持在一个类中.但是,测试的数量很大,它们也是根据功能头分类的.所以他们位于不同的班级.但是,由于它们需要完全相同的设置,因此它们继承了@BeforeClass.因此,每个测试类至少完成一次整个设置,总共花费的时间比我想要的多.

但是,我可以将它们全部放在一个包下的各种子包中,因此如果有办法,我可以为该包中的所有测试运行一次设置,那就太棒了.

Fre*_*tin 19

使用JUnit4测试套件,您可以执行以下操作:

@RunWith(Suite.class)
@Suite.SuiteClasses({ Test1IT.class, Test2IT.class })
public class IntegrationTestSuite
{
    @BeforeClass
    public static void setUp()
    {
        System.out.println("Runs before all tests in the annotation above.");
    }

    @AfterClass
    public static void tearDown()
    {
        System.out.println("Runs after all tests in the annotation above.");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后运行此类,因为您将运行一个普通的测试类,它将运行所有测试.


Aar*_*lla 7

JUnit不支持这一点,你必须使用标准的Java解决方案来实现单例:将公共设置代码移动到静态代码块中,然后在这个类中调用一个空方法:

 static {
     ...init code here...
 }

 public static void init() {} // Empty method to trigger the execution of the block above
Run Code Online (Sandbox Code Playgroud)

确保所有测试都调用init(),例如我将其放入@BeforeClass方法中.或者将静态代码块放入共享基类中.

或者,使用全局变量:

 private static boolean initialize = true;
 public static void init() {
     if(!initialize) return;
     initialize = false;

     ...init code here...
 }
Run Code Online (Sandbox Code Playgroud)