代码之家  ›  专栏  ›  技术社区  ›  Charles Duffy

JUnit:在测试的类中启用断言

  •  27
  • Charles Duffy  · 技术社区  · 16 年前

    assert 在JUnit测试套件中没有失败的语句,因为在JUnit的JVM实例中没有启用断言。明确地说,这些是实现中的“黑盒”断言(检查不变量等),而不是JUnit测试本身定义的断言。当然,我希望在测试套件中捕捉到任何这样的断言失败。

    真的很小心 -enableassertions 无论何时运行JUnit,我更喜欢更健壮的解决方案。另一种方法是将以下测试添加到每个测试类:

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

    有没有一种更自动的方法来实现这一点?JUnit的系统范围配置选项?一个动态的电话 setUp() 方法?

    4 回复  |  直到 16 年前
        1
  •  21
  •   Flow Matt McDonald    11 年前

    在月蚀中你可以去 Windows Preferences Java JUnit ,它有一个要添加的选项 -ea 每次创建新的启动配置时。它添加了 -ea公司 调试配置的选项。

    在创建新的JUnit启动时向VM参数添加'-ea' 配置

        2
  •  5
  •   jitter    16 年前

    我建议有三种可能(简单?)修正了快速测试后对我有效的方法(但是您可能需要检查使用静态初始值设定项块的副作用)

    1.)将静态初始化器块添加到那些依赖于启用断言的测试用例中

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

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

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

    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");
        }
    }
    
        3
  •  4
  •   akuhn    16 年前

    或者,您可以编译代码,使断言 不能 被关掉。在Java6下,您可以使用 "fa.jar – Force assertion check even when not enabled"

        4
  •  1
  •   TofuBeer    16 年前

    就像我一个朋友说的。。。如果要关闭断言,为什么还要花时间编写断言呢?

    考虑到这个逻辑,所有assert语句都应该变成:

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

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

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

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