Sobes.tech
Junior

What is the difference between unit tests and integration tests?

sobes.tech AI

Answer from AI

  • Unit tests verify individual components (classes, methods) in isolation, without external dependencies (databases, external services). The goal is to ensure correctness of the smallest testable parts of the code.
  • Integration tests verify the interaction between multiple components or systems. They involve dependencies and check that different parts of the application work together correctly.

Comparison table:

Aspect Unit tests Integration tests
Scope Single component Interaction of components/systems
Isolation High (mocks, stubs) Low (use real dependencies)
Speed Fast Slower
Complexity Low Higher
Error localization Precise (points to specific component) Harder (can be in any component)
Example Testing logic of a single method Testing database save via service

Example:

// Unit test example
public class CalculatorTest {
    @Test
    public void testAdd() {
        Calculator calc = new Calculator();
        assertEquals(5, calc.add(2, 3));
    }
}
// Integration test example
public class UserServiceIntegrationTest {
    @Autowired
    private UserService userService;

    @Test
    public void testCreateUser() {
        User user = new User("john", "password");
        userService.save(user);
        assertNotNull(userService.findById(user.getId()));
    }
}
What is the difference between unit tests and… - sobes.tech