Junior — Middle
What are the differences between unit and integration tests in their essence and purpose?
sobes.tech AI
Answer from AI
Unit tests check individual, isolated parts of code — usually separate functions or classes. Their goal is to ensure that a specific module works correctly independently of the rest of the system. They are fast, simple, and do not require external resources.
Integration tests verify the interaction between multiple modules or components of the system. They show how parts of the system work together, identifying issues at module interfaces, such as data transfer errors or incorrect integration.
Summary:
- Unit tests — isolated testing of small parts of code.
- Integration tests — testing the cooperation of multiple components.
Example in Java:
// Unit test for a method
@Test
public void testCalculateSum() {
Calculator calc = new Calculator();
assertEquals(5, calc.sum(2, 3));
}
// Integration test that checks the operation of multiple classes together
@Test
public void testUserServiceIntegration() {
UserRepository repo = new UserRepository();
UserService service = new UserService(repo);
User user = service.createUser("John");
assertNotNull(user);
assertEquals("John", user.getName());
}