Hoàng Long Hoàng Long - 2 months ago 16
Java Question

Unit test: assert not work?

I'm applying UnitTest just for a while, and today I met something very strange. Considering the following code:

TestObject alo = null;
assert alo != null; // Pass!!!
Assert.assertNotNull(alo); // Fail, as expected.


I googled around and find that assert is java-built-in, while assertNotNull is JUnit supported. But I can't understand why assert don't complain anything about the null object?

Answer

Hoang, I think you're getting a little confused between Java language asserts and JUnit asserts.

  • The assert keyword in Java was added in 1.4, and intended to allow to verify internal consistency in a class. The best practice recommendation was to use them in private methods to test program invariants. When an assert fails, a java.lang.AssertionError is thrown and is generally not intended to be caught. The idea was they could be enabled during debugging and disabled in production code (which is the default), but frankly, I don't think they ever really caught on. I haven't seen them used much.

  • JUnit also has asserts, in the form of many different static methods in the org.junit.Assert package. These are intended to verify the results of a given test. These asserts also throw a java.lang.AssertionError, but the JUnit framework is set up to catch and record those errors and to generate a report of all failures at the end of the test run. This is the more common usage of asserts, IMO.

You can obviously use either one, but the JUnit asserts are far more expressive, and you don't have to worry about enabling or disabling them. On the other hand, they aren't really for use in business code.

EDIT: Here's a code example that works:

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
  }
}

Here's the output from a run with Java assertions disabled (the 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)
  ...

Here's a run with Java assertions 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)
  ...

Notice in the first example, the Java assert passes, and in the second, it fails.

Comments