Java – unit testing: assertions don’t work?
I've been applying for unit test for some time. Today I met some very strange things Consider the following codes:
TestObject alo = null; assert alo != null; // Pass!!! Assert.assertNotNull(alo); // Fail,as expected.
I googled and found that assert is built in Java and assert not null is supported by JUnit But I can't understand why assertions don't complain about null objects?
Solution
Hoang, I think you're a little confused between Java language assertions and JUnit assertions
>The assert keyword in java was added in 1.4 to allow verification of internal consistency in classes The best practice recommendation is to use them in private methods to test program invariants When the assertion fails, a Java. Net is thrown Lang. assertionerror and is usually not captured The idea is that they can enable them during debugging and disable them in production code (this is the default), but frankly, I don't think they're really popular I don't see them using too much. > JUnit at org junit. There are also assertions in the assert package in the form of many different static methods These are intended to verify the results of a given test These assertions also throw a Java Lang. assertionerror, but the JUnit framework is set to capture and log these errors and generate all failure reports at the end of the test run This is a more common use of assertions, IMO
You can obviously use any of them, but JUnit assertions are more expressive, and you don't have to worry about enabling or disabling them On the other hand, they are not really used in business code
Edit: This is a valid code example:
import org.junit.Assert; import org.junit.Test; public class MyTest { @Test public void test() { Object alo = null; assert alo != null // Line 9 Assert.assertNotNull(alo); // Line 10 } }
This is the run output with Java assertions disabled (default):
c:\workspace\test>java -cp bin;lib\junit-4.8.1.jar org.junit.runner.JUnitCore MyTest JUnit version 4.8.1 .E Time: 0.064 There was 1 failure: 1) test(MyTest) java.lang.AssertionError: at org.junit.Assert.fail(Assert.java:91) ... at MyTest.test(MyTest.java:10) ...
This is a run with Java assertion enabled (- EA):
c:\workspace\test>java -ea -cp bin;lib\junit-4.8.1.jar org.junit.runner.JUnitCore MyTest JUnit version 4.8.1 .E Time: 0.064 There was 1 failure: 1) test(MyTest) java.lang.AssertionError: at MyTest.test(MyTest.java:9) ...
Note that in the first example, the Java assertion is passed, while in the second example, it fails