JUnit: Enable assertions in class under test

女生的网名这么多〃 提交于 2019-12-03 09:30:55
RAbraham

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

The full text next to a check box is

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

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

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

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

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

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");
    }
}

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!