IntelliJ逐个运行测试

时间:2016-09-02 13:15:55

标签: java intellij-idea junit

简短 - 我刚写了一个单身人士课。就像所有的单身人士都是我的私人构造函数的单身人士和包含预定义数量的对象的静态字段。

案例是 - 必须使用JSON文件初始化单例类,并且当没有来自给定列表的文件时,预期的行为是抛出异常。

问题是显然IntelliJ(或者只是JUnit)正在加载所有测试类,然后在一个程序中以随机顺序逐个执行它们。这意味着到达测试错误初始化的类时,单例已经初始化。这意味着每次我一次运行所有测试时,我将有一个测试未通过,当我手动逐个运行时,它将导致所有测试通过。

有没有办法强制IntelliJ运行所有分开的测试类?

修改

我不知道这怎么会改变任何东西,但我们假设它会。以下是具有完全相同行为的示例代码。这是一个IDE问题,而不是java特有的问题。

public class Singleton {
    private static Singleton singleton = new Singleton();

    public static Singleton getInstance() {
        return singleton;
    }

    private Singleton() {
        if (!new File("maybeIExist.txt").exists())
            throw new ExceptionInInitializerError();
    }

    public void doStuff() {
        System.out.println("stuff");
    }
}

当然还有测试:

public class SingletonTestOne {
    @Test(expected = ExceptionInInitializerError.class)
    public void test() throws Exception {
        Singleton.getInstance();
    }
}

第二个:

public class SingletonTestTwo {
    @Before
    public void before() throws Exception {
        //code creating file
    }
    @Test
    public void test() throws Exception {
        Singleton.getInstance();
        doStuff();
    }
    @After
    public void after() throws Exception {
        //code deleting file
    }
}

1 个答案:

答案 0 :(得分:1)

这不是IntelliJ问题,运行mvn test时会遇到同样的问题。您可以通过以下更改来运行测试:

首先更改Singleton类,以便在singleton调用中懒洋洋地创建它的getInstance()字段,请注意此方法现在需要{{1} }。您需要它才能重置该字段。

synchronized

接下来,在您的测试类中,您可以使用反射将public final class Singleton { private static Singleton singleton = null; public static synchronized Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); } return singleton; } private Singleton() { if (!new File("maybeIExist.txt").exists()) { throw new ExceptionInInitializerError(); } } public void doStuff() { System.out.println("stuff"); } } 方法中的singleton字段重置为@Before

null
相关问题