JUnit — Using Assertion
What is JUnit?
It is an open source framework for writing and running unit tests in Java.
For detailed information, you can go to this resource.
Assertion
- void assertEquals(boolean expected, boolean actual)
Checks if two primitives/objects are equal.
2. void assertTrue(boolean condition)
Checks if a condition is true.
3. void assertFalse(boolean condition)
Checks if a condition is false.
4. void assertNotNull(Object object)
Checks that an object is not empty.
5. void assertNull(Object object)
Checks if an object is empty.
6. void assertSame(object1, object2)
The AssertSame() method tests whether two object references point to the same object.
7. void assertNotSame(object1, object2)
assertNotSame() method tests whether two object references point to the same object.
8. void assertArrayEquals(expectedArray, resultArray);
The assertArrayEquals() method tests whether two arrays are equal.
Let’s use some of the methods mentioned above in an example. Create a java class file named TestAssertions.java.
import org.junit.Test;
import static org.junit.Assert.*;
public class TestAssertions {
@Test
public void testAssertions() {
//test data
String str1 = new String ("abc");
String str2 = new String ("abc");
String str3 = null;
String str4 = "abc";
String str5 = "abc";
int val1 = 5;
int val2 = 6;
String[] expectedArray = {"one", "two", "three"};
String[] resultArray = {"one", "two", "three"};
//Check that two objects are equal
assertEquals(str1, str2);
//Check that a condition is true
assertTrue (val1 < val2);
//Check that a condition is false
assertFalse(val1 > val2);
//Check that an object isn't null
assertNotNull(str1);
//Check that an object is null
assertNull(str3);
//Check if two object references point to the same object
assertSame(str4,str5);
//Check if two object references not point to the same object
assertNotSame(str1,str3);
//Check whether two arrays are equal to each other.
assertArrayEquals(expectedArray, resultArray);
}
}
Next, run the test cases.
Verify the output.
true
You can click on this link to access the project.