Junior
What is unit testing?
sobes.tech AI
Answer from AI
Unit testing is the process of testing the smallest isolated part of a program, called a unit (module or component), to confirm that it functions as expected.
- Purpose: To verify the correctness of an individual module.
- Advantages:
- Early detection of errors.
- Improved code quality.
- Facilitation of refactoring.
- Documentation of code functionality.
- Tools: JUnit, Mockito, PowerMock (for Java).
- Principle: Writing test cases that check specific functionality of a unit by providing certain data as input and verifying the expected result or behavior.
- Characteristics of good unit tests:
- Independence: Tests do not depend on each other.
- Automation: Can be executed automatically.
- Speed: Execute quickly.
- Repeatability: Yield the same result every time.
- Isolation: Test only the tested unit, not its dependencies (using mocks).
Example with JUnit:
// Class we want to test
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
// Example of a unit test with JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalculatorTest {
@Test
void testAddPositiveNumbers() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result, "Sum of positive numbers should be correct");
}
@Test
void testAddZero() {
Calculator calculator = new Calculator();
int result = calculator.add(0, 5);
assertEquals(5, result, "Sum with zero should be correct");
}
}