In this tutorial we will learn how to use JUnit assertions. An assertion is one of a number of static methods on the org.junit.jupiter.api.Assertions class. Assertions are used to test a condition that must evaluate to true in order for the test to continue executing.

If an assertion fails, the test is halted at the line of code where the assertion is located, and the assertion failure is reported. If the assertion succeeds, the test continues to the next line of code. JUnit Jupiter, comes with many of assertion methods that JUnit 4 has and adds some overloads which can be used with Java 8 Lambda Expression. Let's see them in detail:

assertAll

AssertAll can be used to verify a group of conditions. The interesting thing about assertAll is that it always checks all of the assertions that are passed to it, no matter how many fail. If all pass, all is fine - if at least one fails you get a detailed result of all that went wrong.

It is best used for asserting a set of properties that belong together conceptionally. Example: assume you have a simple class like an address with fields city, street, number and would like to assert that those are what you expect them to be:

Address address = addressFactory.buildAddress();
assertEquals("New York", address.getCity());
assertEquals("Park avenue", address.getStreet());
assertEquals("1250", address.getNumber());

Now, as soon as the first assertion fails, you will never see the results of the second, which can be an issue. Using assertAll can be the right approach. Indeed, if the method returns the wrong address, you will still see the following error stack trace:

    (3 failures)
    expected: <New York> but was: <Philadelphia>
    expected: <Park avenue> but was: <street 51>
    expected: <1250> but was: <126>

Please notice that you coule use also the lamda syntax as well:

Address address = addressFactory.buildAddress();
assertAll("Checking full address",
    () -> assertEquals("New York", address.getCity()),
    () -> assertEquals("Park avenue", address.getStreet()),
    () -> assertEquals("1250", address.getNumber())

assertNull

Asserts that an object is null. If it isn't an AssertionError is thrown:

 @Test
  public void testWithNull() {
     
    Integer year = null;     
    assertNull(year, "The year is not null");
   
}

assertNotNull

Asserts that an object is not null. If it isn't an AssertionError is thrown:

 @Test
  public void testWithNull() {
     
    Integer year = 2019;     
    assertNotNull(year, "The year is not null");
   
}

assertThrows

An expected exception is considered to be just another condition that can be asserted, and thus Assertions contains methods to handle this. Example:

@Test()
@DisplayName("Empty argument")
public void testAdd_ZeroOperands_EmptyArgument() {
  long[] numbersToSum = {};
  assertThrows(IllegalArgumentException.class, () ‑> classUnderTest.add(numbersToSum));
}

 @Test
  public void testIsNullOrBlankOK() {
    // Test the case that the input is NULL
    String input = null;

    assertTrue(StringUtils.isNullOrBlank(input));
  
    // Test case with the input is empty
    input = " ";
    assertTrue(StringUtils.isNullOrBlank(input));

    // Test case with the input is not empty
    input = "abc";

    assertFalse(StringUtils.isNullOrBlank(input));

  }

assertSame and assertNotSame

assertSame checks the object reference using the == operator. Here is an example:

BigDecimal b1 = new BigDecimal("500");
BigDecimal b2 = new BigDecimal("500");
BigDecimal b3 = b1;
 
int i1 = 10;
int i2 = 10;
 
  @Test
  public void BigDecimaltest() throws Exception {
    // if(b1 == b2)
    assertSame(b1, b2);    // FAILS!
 
    // b1.equals(b2)
    assertEquals(b1, b2);  // PASSES!
 
    // (b1 == b3)
    assertSame(b1, b3);    // PASSES!
 
    //(b1.equals(b3))
    assertEquals(b1, b3);  // PASSES!
  }


    assertNotSame(defaultSt, actual, () -> "Expected ouput is same with actual");

assertEquals

Check two objects/primitive values using the following rule:

  • If primitive values are passed and then the values are compared.
  • If objects are passed, then the equals() method is invoked.
  @Test
  public void testConcatWithRegularInput() {
    String st1 = "Hello";
    String st2 = "World";
    String st3 = "!";
    String expect = st1 + st2 + st3;
    String actual = StringUtils.concat(st1, st2, st3);
    assertEquals(expect, actual);
}

What is the difference between assertions and assumptions? The difference can be subtle, so use this rule of thumb: Use assertions to check the results of a test method. Use assumptions to determine whether to run the test method at all. An aborted test is not reported as a failure, meaning that failure won’t break the build.

 

 

FREE WildFly Application Server - JBoss - Quarkus - Drools Tutorials