如何让AssertTrue指出为什么测试失败像AssertEquals?

时间:2015-03-01 15:29:33

标签: java junit tdd

的assertEquals

assertEquals(5,assignment.getAssignment());

结果:

Running tests
Test running started
junit.framework.AssertionFailedError: expected:<5> but was:<1       1       1       1       1       >
at com.it030.numbersequences.AssignmentTest.testAssignmentAndPossibleAnswers(AssignmentTest.java:12)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)

很明显出了什么问题。


AssertTrue

Assert.assertTrue(assignment.getAssignment().replaceAll("\\s", "")
    .matches("^1(1((1){3}|235)|361015)$"));

结果:

Running tests
Test running started
junit.framework.AssertionFailedError
at com.it030.numbersequences.AssignmentTest.testAssignmentAndPossibleAnswers(AssignmentTest.java:14)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)

目前还不清楚出了什么问题。

1 个答案:

答案 0 :(得分:3)

所有assert *方法都有一个变体,您可以在其中添加测试失败时显示的String。

因此,只需使用此消息添加一条消息,其中包含有关失败的更多上下文。

 public static void assertTrue(String message,
                          boolean condition)

示例:

String replaced = assignment.getAssignment().replaceAll("\\s", "");
String msg = replaced+" does not match regexp ^1(1((1){3}|235)|361015)$";
Assert.assertTrue(msg , replaced
      .matches("^1(1((1){3}|235)|361015)$"));

结果:

Running tests
Test running started
junit.framework.AssertionFailedError: 2461016 does not match regexp ^1(1((1){3}|235)|361015)$
at com.it030.numbersequences.AssignmentTest.testAssignmentAndPossibleAnswers(AssignmentTest.java:18)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)