2014-02-28 95 views
3

我使用JUnit断言消息输出一些调试信息:JUnit的延迟断言消息创建

assertEquals(debugString, a, b); 

这个字符串的创新是昂贵的,我要创建它只有在断言失败。我怎样才能做到这一点?

+0

JUnit的标准Assert不支持延迟创建错误消息。你有看过Hamcrest吗?它具有很好的错误消息,只有在测试失败AFAIK时才会创建。 –

+0

@StefanBirkner我没有。看起来不错。请给出答案 – leventov

回答

2

这是一个黑客,但你可以使用if s和fail来模拟所有的断言。例如,而不是:

assertEquals(debugString, a, b); 

您的测试可能有:

if (!a.equals(b)) { 
    fail (debugString); 
} 
1

你可以使用Hamcrest,这就造成只有在失败AFAIK消息。

String x ="x"; 
String y="y"; 
assertThat(x, is(equalTo(y)); 

在出现故障的情况下,它产生

java.lang.AssertionError: 
Expected: is "y" 
    but: was "x" 
0

您可以赶上Asse田,然后用你的信息重新抛出。一些示例代码,我只是写了超过100倍的速度,当消息创建感动圈外:

@Test 
public void shouldHaveCorrectParameters() { 
    for(int r = 1; r <= 50; r++) { 
    for(int mce = 1; mce <= 64; mce++) { 
     Encoder encoder = new Encoder(r, mce); 

     for(int l = 1; l <= 16384; l++) { 
     EncodeParameters params = encoder.determineParameters(l); 
     double effectiveRedundancy = (params.n - params.k) * 100/(double)params.k; 

     try { 
      assertTrue(params.n - params.k >= mce); 
      assertTrue(params.n - params.k <= mce * 2); 
      assertTrue(effectiveRedundancy >= r); 
     } 
     catch(AssertionError e) { 
      String msg = "redundancy=" + r + "%; minimumCorrectableErrors=" + mce + "; fileLength=" + l + "; k=" + params.k + "; n=" + params.n + String.format("; effectiveRedundancy=%.3f%%", effectiveRedundancy); 

      throw new AssertionError(msg, e); 
     } 
     } 
    } 
    } 
} 
1

为了完整起见,一旦JUnit的5可用,你就可以用一个函数参数创建的消息,只有在断言失败时才被评估。它的形式可能是这样的:

assertTrue(() -> expensiveMessage(), testResult == expectedResult);