When we develop a test case, we have one expected output and one actual output. Assertion helps us compare these outputs and evaluate whether a given test case is pass or fail.
We can use assertion in JUnit after we import it into the file:
import static org.junit.Assert.*;
All assertion methods are available in JUnit
assertclass.
The JUnit provides all assert methods by default.
Let’s take a look at few assert methods:
Let’s take a look at a few assertion examples.
import static org.junit.Assert.*;
import org.junit.*;
public class assertTest {
//assertEqual compares two strings
@Test
public void assertEquslTest() {
String stractual = "This is the testcase1";
assertEquals("This is the testcase1", stractual);
}
//assertArrayEqualsTest compares two array
@Test
public void assertArrayEqualsTest() {
int expected[] = {1,2,3,4,5};
int actual[] = {1,2,3,4,5};
assertArrayEquals(expected, actual);
}
//assertFalse checks value is false
@Test
public void assertFalseTest() {
boolean value = false;
assertFalse(value);
}
//assertTrue checks value is true
@Test
public void assertTrueTest() {
boolean value = true;
assertTrue(value);
}
}OK (4 tests) shows that all 4 test cases are passing.
If one of these test cases fails, the output will be Tests run: 4, Failures: 1.
Free Resources