What is JUnit primarily used for in Java?

Java MCQ: What is JUnit primarily used for in Java?

a) Building graphical user interfaces
b) Managing databases
c) Unit testing
d) Handling network communications

Answer:

c) Unit testing

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.

Reference links:

https://junit.org/junit5/

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top