JUnit:在被测类中启用断言 [英] JUnit: Enable assertions in class under test

查看:124
本文介绍了JUnit:在被测类中启用断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Java assert语句在JUnit测试套件中没有失败,这让我有些烦恼,因为在JUnit的JVM实例中未启用断言.需要明确的是,这些是实现(检查不变式等)内部的黑匣子"断言,而不是JUnit测试自身定义的断言.当然,我想在测试套件中捕获所有此类断言失败.

I've been bit a few times by Java assert statements 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.

显而易见的解决方案是,每当我运行JUnit时,都要非常小心使用-enableassertions,但是我希望使用更可靠的解决方案.一种替代方法是在每个测试类中添加以下测试:

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

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

是否有更自动的方式来完成此任务? JUnit的系统范围配置选项?我可以在setUp()方法中进行动态调用吗?

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?

推荐答案

在Eclipse中,您可以转到WindowsPreferencesJavaJUnit,可以选择在每次创建新的启动配置时添加-ea.还将-ea选项也添加到调试配置"中.

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.

复选框旁边的全文是

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

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

这篇关于JUnit:在被测类中启用断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆