Java MCQ: Which method is used to assert that a condition is true in JUnit?
a) assertTrue()
b) assertCondition()
c) assertMatch()
d) assertEquals()
Answer:
a) assertTrue()
Explanation:
The assertTrue()
method is used in JUnit to assert that a condition is true. If the condition is true, the test passes; if it is false, the test fails. This method is commonly used to validate boolean conditions in the code being tested.
Here’s an example:
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class CalculatorTest {
@Test
public void testIsPositive() {
Calculator calc = new Calculator();
boolean result = calc.isPositive(5);
assertTrue(result, "The number should be positive");
}
}
In this example, assertTrue(result)
checks that the isPositive
method of the Calculator
class returns true
for the input 5
. If the condition is true, the test will pass; otherwise, it will fail, and the message “The number should be positive” will be displayed.
The assertTrue()
method is essential for validating conditions that are expected to be true as part of the test case.