Java MCQ: Which assertion is used to check that two values are equal in JUnit?
a) assertSame()
b) assertEqual()
c) assertEquals()
d) assertMatch()
Answer:
c) assertEquals()
Explanation:
The assertEquals()
assertion is used in JUnit to check that two values are equal. This assertion compares the expected value with the actual value and passes the test if they are equal. If they are not equal, the test fails, and an error message is generated.
Here’s an example of using assertEquals()
:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
int result = calc.add(2, 3);
assertEquals(5, result, "The addition result should be 5");
}
}
In this example, assertEquals(5, result)
checks that the result of the add
method is equal to 5. If the values are not equal, the test will fail, and the message “The addition result should be 5” will be displayed.
Assertions like assertEquals()
are essential for verifying that the code behaves as expected during testing.