Interview Questions

What Happens If You Run JUnit Tests with Java Assertion Enabled?

JUnit Questions and Answers


(Continued from previous question...)

What Happens If You Run JUnit Tests with Java Assertion Enabled?

As of JUnit 3.8, The JUnit runner will work nicely with Java assertion feature. If Java assertion is enabled and a Java "assert" statement fails, the JUnit runner will report this in same way as the calling test fails.

If you are using the test class, DayOfWeekTest.java, presented in the previous question, Here is the error report when executed with the "-ea" option, enabling Java assertion:

java -ea -cp
.;\local\junit4.4\junit-4.4.jar 
org.junit.runner.JUnitCore DayOfWeekTest
JUnit version 4.4
...E
Time: 0
There was 1 failure:
1) test3(DayOfWeekTest)
java.lang.AssertionError: -2
 at DayOfWeek.getDayOfWeek(DayOfWeek.java:34)
 at DayOfWeekTest.test3(DayOfWeekTest.java:20)
 at sun.reflect.NativeMethodAccessorImpl.invoke0
 (Native Method)
 ...

FAILURES!!!
Tests run: 3,  Failures: 1

test3() failed with the Java "assert" statement inside the getDayOfWeek() method, not the JUnit assertTrue() call. In other work, the code problem is caught by the Java "assert" statement, not by the JUnit test.

(Continued on next question...)

Other Interview Questions