Sobes.tech
Junior

What is unit testing?

sobes.tech AI

Answer from AI

Unit testing is a method of testing software where the smallest isolated parts of an application, called units or modules, are tested. Usually, these are individual classes or methods.

Goals of unit testing:

  • Detect defects early in development.
  • Improve code quality and reliability.
  • Simplify refactoring.
  • Serve as documentation for the code.

Advantages:

  • Fast execution of tests.
  • Easy to locate errors.
  • Increase confidence in code correctness.

Tools for unit testing in Java:

  • JUnit
  • TestNG
  • Mockito (for creating mock objects)

Example of a simple unit test using JUnit:

class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

// Test class
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class CalculatorTest {

    @Test // @Test annotation indicates a test method
    void testAdd() {
        Calculator calculator = new Calculator();
        int result = calculator.add(2, 3);
        assertEquals(5, result, "2 + 3 should equal 5"); // Check expected result
    }
}