java JUnit:在被测类中启用断言

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1798016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:01:29  来源:igfitidea点击:

JUnit: Enable assertions in class under test

javajunitassertions

提问by Chris Conway

I've been bit a few times by Java assertstatements that didn't fail in the JUnit test suite because assertions weren't enabled in JUnit's JVM instance. To be clear, these are "black box" assertions inside implementations (checking invariants, etc) not the assertions defined by the JUnit tests themselves. Of course, I'd like to catch any such assertion failures in the test suite.

我被assertJUnit 测试套件中没有失败的 Java语句咬了几次,因为在 JUnit 的 JVM 实例中没有启用断言。需要明确的是,这些是实现内部的“黑匣子”断言(检查不变量等),而不是 JUnit 测试本身定义的断言。当然,我想在测试套件中捕获任何此类断言失败。

The obvious solution is to be really carefulto use -enableassertionswhenever I run JUnit, but I'd prefer a more robust solution. One alternative is to add the following test to every test class:

显而易见的解决方案是在我运行 JUnit 时非常小心地使用-enableassertions,但我更喜欢更强大的解决方案。一种替代方法是将以下测试添加到每个测试类:

  @Test(expected=AssertionError.class)
  public void testAssertionsEnabled() {
    assert(false);
  }

Is there a more automatic way to accomplish this? A system-wide configuration option to JUnit? A dynamic call I could put in the setUp()method?

有没有更自动的方法来完成这个?JUnit 的系统范围配置选项?我可以在setUp()方法中放入动态调用吗?

回答by RAbraham

In Eclipse you can go to WindowsPreferencesJavaJUnit, which has an option to add -eaeverytime a new launch configuration is created. It adds the -eaoption to the Debug Configuration as well.

在 Eclipse 中,您可以转到WindowsPreferencesJavaJUnit-ea每次创建新的启动配置时都有一个添加选项。它还-ea向调试配置添加了该选项。

The full text next to a check box is

复选框旁边的全文是

Add '-ea' to VM arguments when creating a new JUnit launch configuration

创建新的 JUnit 启动配置时将“-ea”添加到 VM 参数

回答by jitter

I propose three possible (simple?) fixes which work for me after a quick test (but you might need to check the side effects of using a static-initializer-block)

我提出了三个可能的(简单的?)修复程序,它们在快速测试后对我有用(但您可能需要检查使用静态初始化块的副作用)

1.) Add a static-initializer block to those testcases which rely on assertions being enabled

1.) 向那些依赖于启用断言的测试用例添加一个静态初始化块

import ....
public class TestXX....
...
    static {
        ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
    }
   ...
   @Test(expected=AssertionError.class)
   ...
...

2.) Create a base-class which all of your test-classes extend which need assertions enabled

2.) 创建一个基类,您的所有测试类都扩展它,需要启用断言

public class AssertionBaseTest {
    static {
        //static block gets inherited too
        ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
    }
}

3.) Create a test suite which runs all your test

3.) 创建一个运行所有测试的测试套件

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
    //list of comma-separated classes
    /*Foo.class,
    Bar.class*/
})
public class AssertionTestSuite {
    static {
        //should run before the test classes are loaded
        ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
    }
    public static void main(String args[]) {
        org.junit.runner.JUnitCore.main("AssertionTestSuite");
    }
}

回答by akuhn

Alternatively, you may compile your code such that assertions cannotbe turned off. Under Java 6, you may use "fa.jar – Force assertion check even when not enabled", a small hack of mine.

或者,您可以编译代码以使断言无法关闭。在 Java 6 下,您可以使用“fa.jar – 即使未启用也强制断言检查”,这是我的一个小技巧。

回答by TofuBeer

As a friend of mine says... why take the time to write an assert if you are just going to turn it off?

正如我的一个朋友所说......如果你只是想把它关掉,为什么要花时间写断言呢?

Given that logic all assert statements should become:

鉴于该逻辑,所有断言语句都应变为:

if(!(....))
{
    // or some other appropriate RuntimeException subclass
    throw new IllegalArgumentException("........."); 
}

To answer your question a way you probably want :-)

以您可能想要的方式回答您的问题:-)

import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;


@RunWith(Suite.class)
@Suite.SuiteClasses({
        FooTest.class,
        BarTest.class
        })
public class TestSuite
{
    @BeforeClass
    public static void oneTimeSetUp()
    {
        ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
    }
}

Then run the test suite rather than each test. This should (works in my testing, but I did not read the internals of the JUnit framework code) result in the assertion status being set before any of the test classes are loaded.

然后运行测试套件而不是每个测试。这应该(在我的测试中有效,但我没有阅读 JUnit 框架代码的内部结构)导致在加载任何测试类之前设置断言状态。