javaunit-testingjunit

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?


Solution

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

    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.