fail() method belongs to JUnit 4 org.junit.Assert class. 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 create a largest(final int[] list) method to find the largest number in an array. We will write JUnit test for largest(final int[] list) method.
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;
}
@Test
public void testEmpty() {
try {
largest(new int[] {});
fail("Should have thrown an exception");
} catch (final RuntimeException e) {
assertTrue(true);
}
}
}
Output:
Related JUnit Examples
- JUnit Assert.assertArrayEquals() Method Example
- JUnit Assert.assertEquals() Method Example
- JUnit Assert.assertTrue() Method Example
- JUnit Assert.assertFalse() Method Example
- JUnit Assert.assertNull() Method Example
- JUnit Assert.assertNotNull() Method Example
- JUnit Assert.assertSame() Method Example
- JUnit Assert.assertNotSame() Method Example
- JUnit Assert.fail() Method Example
Comments
Post a Comment