JUnit Assert.fail() Method Example

In this post, we will demonstrate how to use Assert.fail() method with an example.

The fail() method belongs to JUnit 4 org.junit.Assert class.

The fail assertion fails a test throwing an AssertionError. It can be used to verify that an actual exception is thrown or when we want to make a test failing during its development.
Check out JUnit 5 tutorials and examples at https://www.javaguides.net/p/junit-5.html
In JUnit 5 all JUnit 4 assertion methods are moved to org.junit.jupiter.api.Assertions class.

void org.junit.Assert.fail(String message)

Fails a test with the given message. 
Parameters:
  • message the identifying message for the AssertionError (null okay)

Assert.fail(String message) Method Example

Let's first create the largest(final int[] list) method to find the largest number in an array:
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class AssertFailExample {

 public int largest(final int[] list) {
      int index, max = Integer.MAX_VALUE;
      for (index = 0; index < list.length - 1; index++) {
         if (list[index] > max) {
             max = list[index];
         }
      }
      return max;
 }
 
Let's write the JUnit test for above largest(final int[] list) method:
@Test
 public void testEmpty() {
     try {
         largest(new int[] {});
         fail("Should have thrown an exception");
     } catch (final RuntimeException e) {
         assertTrue(true);
     }
   } 
}

Output:

Comments