Java MCQ: What is JUnit primarily used for in Java?
Answer:
Explanation:
JUnit is a widely-used testing framework in Java that is primarily designed for writing and running unit tests. Unit testing involves testing individual components or units of code (such as methods or classes) to ensure they work as expected. JUnit provides annotations, assertions, and test runners that facilitate the creation and execution of tests, making it easier for developers to identify and fix bugs early in the development process.
Here’s a simple example of a JUnit test case:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
int result = calc.add(2, 3);
assertEquals(5, result);
}
}
In this example, the testAdd
method tests the add
method of the Calculator
class to ensure it returns the correct sum of two numbers.
JUnit helps improve code quality and reliability by enabling automated testing, which is an essential practice in software development.