Close

JUnit - Assertions

[Last Updated: Nov 4, 2018]

In this tutorial, we will quickly walk-through org. junit. Assert class methods with examples.

Assert.assertTrue(..) and Assert.assertFalse(..)

These assert methods confirm that a condition is true or not.

public class AssertionExample {

  @Test
  public void test1() {
      String str = "test string";
      Assert.assertTrue("str cannot be empty", str != null && str.length() != 0);
      Assert.assertFalse("str cannot by empty", str == null || str.length() == 0);
  }
    .............
}
mvn -q test -Dtest=AssertionExample#test1

Output

d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test1

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.041 sec - in com.logicbig.example.AssertionExample

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

In above example, we are running only one test method using maven 'test' command. Check out the related tutorial here.

All method in Assert class comes with two overloaded variants; one accepts an extra message parameter to show when assertion fails. Assert methods internally throw java. lang. Assertion Error when the specified condition does not satisfy.

Let's write a test that fails:

public class AssertionExample {
    .............
  @Test
  public void test2() {
      String str = null;
      Assert.assertTrue("str cannot be empty", str != null && str.length() != 0);
  }
    .............
}
mvn -q test -Dtest=AssertionExample#test2

Output

d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test2

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.049 sec <<< FAILURE! - in com.logicbig.example.AssertionExample
test2(com.logicbig.example.AssertionExample) Time elapsed: 0.007 sec <<< FAILURE!
java.lang.AssertionError: str cannot be empty
at com.logicbig.example.AssertionExample.test2(AssertionExample.java:21)


Results :

Failed tests:
AssertionExample.test2:21 str cannot be empty

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project junit-assertions: There are test failures.
[ERROR]
[ERROR] Please refer to D:\example-projects\junit\junit-assertions\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

assertEquals(..)

These methods assert that two objects are equal by internally calling Object#equals(..) method.

public class AssertionExample {
    .............
  @Test
  public void test3() {
      Number a = new Integer(5);
      Assert.assertEquals("The number is not 5", a, 5);
  }
    .............
}
mvn -q test -Dtest=AssertionExample#test3

Output

d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test3

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec - in com.logicbig.example.AssertionExample

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

If both of the objects are null then test passes, if one of them is null then the test fails without throwing NullPointerException.

Other Overloaded variants of assertEquals(..)

There are overloaded variants of these methods which accepts primitives. This is to avoid autoboxing and hence making these method calls more efficient.

There's one more overloaded version of these methods for double comparision which provide an option to specify delta (acceptable positive/negative difference):

public static void assertEquals(String message,
                                double expected,
                                double actual,
                                double delta)
public class AssertionExample {
    .............
  @Test
  public void test4() {
      double d = 2.6;
      Assert.assertEquals("The numbers are not approximately equal", d, 3, 0.5);
  }
    .............
}
mvn -q test -Dtest=AssertionExample#test4

Output

d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test4

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.049 sec - in com.logicbig.example.AssertionExample

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

assertArrayEquals(..)

These overloaded methods internally use Arrays.deepEquals() for array comparision. Each elements are checked for being equal individually. Check out the difference between Arrays.equals, Arrays.deepEquals and equals.

public class AssertionExample {
    .............
  @Test
  public void test5() {
      int[] integers = {3, 5, 7};
      Assert.assertArrayEquals("The numbers are not equal", integers, new int[]{3, 5, 7});
  }

  @Test
  public void test6() {
      Object[] integers = {3, 5, new int[]{7, 9}};
      Assert.assertArrayEquals("The numbers are not equal", integers,
              new Object[]{3, 5, new int[]{7, 9}});
  }
    .............
}
mvn -q test "-Dtest=AssertionExample#test5, AssertionExample#test6"

Output

d:\example-projects\junit\junit-assertions>mvn -q test "-Dtest=AssertionExample#test5, AssertionExample#test6"

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.049 sec - in com.logicbig.example.AssertionExample

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

There are overloaded versions of assertArrayEquals(..) which accepts primitives or Objects parameters.


assertSame(..) and assertNotSame(..)

These overloaded methods compare the objects based on '==' and not based on 'equals' method.

public class AssertionExample {
    .............
  @Test
  public void test7() {
      String str1 = new String("test string");
      String str2 = new String("test string");
      Assert.assertSame("Same objects reference failed", str1, str1);
      Assert.assertNotSame("Different objects not same failed", str2, str1);
      Assert.assertSame("Different objects reference but have same value failed", str2, str1);
  }
    .............
}
mvn -q test -Dtest=AssertionExample#test7

Output

d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test7

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.051 sec <<< FAILURE! - in com.logicbig.example.AssertionExample
test7(com.logicbig.example.AssertionExample) Time elapsed: 0.006 sec <<< FAILURE!
java.lang.AssertionError: Different objects reference but have same value failed expected same:<test string> was not:<test string>
at com.logicbig.example.AssertionExample.test7(AssertionExample.java:55)


Results :

Failed tests:
AssertionExample.test7:55 Different objects reference but have same value failed expected same:<test string> was not:<test string>

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project junit-assertions: There are test failures.
[ERROR]
[ERROR] Please refer to D:\example-projects\junit\junit-assertions\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

In above output the last call of assertSame fails.


assertThat(..)

These methods satisfy the condition provided by a matcher object. Here's the signature of one of these methods:

public static <T> void assertThat(java.lang.String reason,
                                  T actual,
                                  org.hamcrest.Matcher<T> matcher)

Hamcrest is a third party library used by JUnit framework. Hamcrest provides a generic way to create expression to check conditions. The interface Matcher is given by:

public interface Matcher<T> extends SelfDescribing {
    boolean matches(Object var1);

    void describeMismatch(Object var1, Description var2);

    /** @deprecated */
    @Deprecated
    void _dont_implement_Matcher___instead_extend_BaseMatcher_();
}

We would probably want to extend BaseMatcher instead of implementing this interface. Here's an example which checks if the expected number is a multiple of 2 or not.

public class AssertionExample {
    .............
  @Test
  public void test9() {
      int i = 22;
      Assert.assertThat(i, createMultipleOfTwoMatcher());
  }

  private BaseMatcher<Integer> createMultipleOfTwoMatcher() {
      return new BaseMatcher<Integer>() {

          @Override
          public void describeTo(Description description) {
              description.appendText("Not a multiple of 2.");
          }

          @Override
          public boolean matches(Object item) {
              Integer integer = (Integer) item;
              return integer != null && integer % 2 == 0;
          }
      };
  }
    .............
}
mvn -q test -Dtest=AssertionExample#test9

Output

d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test9

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.051 sec - in com.logicbig.example.AssertionExample

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

Following fails which uses an instance of the same matcher class:

public class AssertionExample {
    .............
  @Test
  public void test10() {
      int i = 23;
      Assert.assertThat(i, createMultipleOfTwoMatcher());
  }
    .............
}
mvn -q test -Dtest=AssertionExample#test10

Output

d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test10

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.054 sec <<< FAILURE! - in com.logicbig.example.AssertionExample
test10(com.logicbig.example.AssertionExample) Time elapsed: 0.008 sec <<< FAILURE!
java.lang.AssertionError:

Expected: Not a multiple of 2.
but: was <23>
at com.logicbig.example.AssertionExample.test10(AssertionExample.java:90)


Results :

Failed tests:
AssertionExample.test10:90
Expected: Not a multiple of 2.
but: was <23>

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project junit-assertions: There are test failures.
[ERROR]
[ERROR] Please refer to D:\example-projects\junit\junit-assertions\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

org.hamcrest.CoreMatchers provides various out of the box implementations of Matcher (accessible via static methods) :

public class AssertionExample {
    .............
  @Test
  public void test8() {
      int i = 22;
      Assert.assertThat("The number is not 22", i, CoreMatchers.is(22));
      Assert.assertThat("The number is 23", i, CoreMatchers.not(23));
  }
    .............
}
mvn -q test -Dtest=AssertionExample#test8

Output

d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test8

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec - in com.logicbig.example.AssertionExample

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

assertNull(..) and assetNotNull(..)

These methods assert that an object is null or not null respectively.

public class AssertionExample {
    .............
  @Test
  public void test11() {
      String str = "test string";
      String str2 = null;
      Assert.assertNotNull("The str is null.", str);
      Assert.assertNull("The str is not null.", str2);
  }
    .............
}
mvn -q test -Dtest=AssertionExample#test11

Output

d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test11

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.041 sec - in com.logicbig.example.AssertionExample

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

fail(..)

These methods are used to fail a test manually. We will probably want to do that if we want to test the condition ourselves:

public class AssertionExample {
    .............
  @Test
  public void test12() {
      String str = null;
      if (str == null) {
          Assert.fail("The provided str is null");
      }
  }
}
mvn -q test -Dtest=AssertionExample#test12

Output

d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test12

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.05 sec <<< FAILURE! - in com.logicbig.example.AssertionExample
test12(com.logicbig.example.AssertionExample) Time elapsed: 0.006 sec <<< FAILURE!
java.lang.AssertionError: The provided str is null
at com.logicbig.example.AssertionExample.test12(AssertionExample.java:105)


Results :

Failed tests:
AssertionExample.test12:105 The provided str is null

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project junit-assertions: There are test failures.
[ERROR]
[ERROR] Please refer to D:\example-projects\junit\junit-assertions\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Example Project

Dependencies and Technologies Used:

  • junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • maven-surefire-plugin 2.19.1: Maven Surefire MOJO in maven-surefire-plugin.
  • surefire-junit4 2.19.1: SureFire JUnit 4.0+ Runner.
  • JDK 1.8
  • Maven 3.3.9

Junit Assert Examples Select All Download
  • junit-assertions
    • src
      • test
        • java
          • com
            • logicbig
              • example
                • AssertionExample.java

    See Also