Junior — Middle
How is the testing of individual code components carried out using unit tests?
sobes.tech AI
Answer from AI
Unit tests verify individual components of code (methods, functions) in isolation from the rest of the system to ensure they work correctly.
In Java, JUnit is often used for this purpose. The main steps are:
- A test class is created, where a separate test is written for each method being tested.
- Input data and the expected result are specified in the tests.
- Assertions are used to check that the actual result matches the expected one.
An example of a simple unit test with JUnit 5:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void testAdd() {
Calculator calc = new Calculator();
int result = calc.add(2, 3);
assertEquals(5, result);
}
}
This approach helps quickly identify errors at the level of individual components and facilitates code maintenance.