如何为junit测试设置测试名称-但不使用测试方法的名称?

时间:2019-06-17 05:04:03

标签: java junit

我有复杂的junit测试。我要设置此测试的名称/说明,只有在测试失败时才会显示,否则我只需要简单的名称即可。

我可以用常见的方法来做,并使用测试方法的名称作为对此方法的描述。

@Test
/**
 * Should return something when some parameter is set to specific value 
 * and other parameter is set to another specific value and everything is
 * executed in specific context under specific environment
 */
public void test42() {
    ....
}

@Test()
//not like that
public void shouldReturnSomethingWhenSomeParameterIsSetToSpecificValueAndOtherParameterIs SetToAnotherSpecificValueAandEverythingIsExecutedInSpecificContextUnderSpecificEnvironment() {
    ....
}

期望是在测试失败时将公开来自命令的描述。 像这样:

[INFO] Results:
[INFO]
[ERROR] Failures: 
[ERROR]   FooTest.test42:110 
[ERROR]   > Should return something when some parameter is set to specific value 
[ERROR]   > and other parameter is set to another specific value and everything is
[ERROR]   > executed in specific context under specific environment
Expecting:
  <[8, 3]>
to contain only:
  <[9, 2]>
elements not found:
  <[9, 2]>
and elements not expected:
  <[8, 3]>

[INFO]
[ERROR] Tests run: 85, Failures: 1, Errors: 0, Skipped: 0

1 个答案:

答案 0 :(得分:1)

@Test接口没有任何此类值。但是是断言错误使测试失败,因此您可以向特定的断言添加一条消息,例如:

assertTrue("Those are not equal", 0 == 1);

或者例如,使用hamcrest可以传递原因:

assertThat("Those should be equal", 0, is(equalTo(0)));

消息将在失败时打印。