Assertion in Junit
In JUnit, assertions are used to verify the expected behavior of your code during testing. They allow you to check if certain conditions are true or false and report the test results accordingly. If an assertion fails, the test is considered to have failed.
JUnit provides a set of static methods in the Assertions class (JUnit 5) or Assert class (JUnit 4) for making assertions. Here are some common assertion methods:
- assertEquals(expected, actual): This assertion checks if the expected value is equal to the actual value.
import org.junit.jupiter.api.Assertions;
@Test
public void testAddition() {
int result = add(3, 5);
Assertions.assertEquals(8, result);
}
- assertTrue(condition): This assertion checks if the given condition is true.
import org.junit.jupiter.api.Assertions;
@Test
public void testIsPositive() {
int number = 10;
Assertions.assertTrue(number > 0);
}
- assertFalse(condition): This assertion checks if the given condition is false.
import org.junit.jupiter.api.Assertions;
@Test
public void testIsNegative() {
int number = -5;
Assertions.assertFalse(number > 0);
}
- assertNull(object): This assertion checks if the given object is null.
import org.junit.jupiter.api.Assertions;
@Test
public void testIsNull() {
Object obj = null;
Assertions.assertNull(obj);
}
- assertNotNull(object): This assertion checks if the given object is not null.
import org.junit.jupiter.api.Assertions;
@Test
public void testIsNotNull() {
Object obj = new Object();
Assertions.assertNotNull(obj);
}
- assertSame(expected, actual): This assertion checks if the expected and actual references point to the same object.
import org.junit.jupiter.api.Assertions;
@Test
public void testSameReference() {
Object obj1 = new Object();
Object obj2 = obj1;
Assertions.assertSame(obj1, obj2);
}
- assertNotSame(expected, actual): This assertion checks if the expected and actual references do not point to the same object.
import org.junit.jupiter.api.Assertions;
@Test
public void testDifferentReferences() {
Object obj1 = new Object();
Object obj2 = new Object();
Assertions.assertNotSame(obj1, obj2);
}
- assertThrows(exceptionType, executable): This assertion checks if the executable throws an exception of the specified exceptionType.
import org.junit.jupiter.api.Assertions;
@Test
public void testDivideByZero() {
int a = 10;
int b = 0;
Assertions.assertThrows(ArithmeticException.class, () -> divide(a, b));
}
These are some of the commonly used assertion methods in JUnit. Depending on the version of JUnit you are using (JUnit 5 or JUnit 4), the assertion methods may have slight differences in naming and package import. Always make sure to import the appropriate assertion class based on your JUnit version.
No comments:
Post a Comment