Junior — Middle
How to distinguish unit tests from integration tests and what are their main differences?
sobes.tech AI
Answer from AI
Unit tests check individual, isolated parts of code — usually functions or methods — without dependencies on external systems. They are fast, simple, and help ensure that a specific piece of logic works correctly.
Integration tests verify the interaction between multiple components or modules of a system, including working with databases, networks, files, and other external services. They are more complex and slower but are important for verifying the system's integrity.
Main differences:
-
Scope of testing:
- Unit — individual functions/classes.
- Integration — interaction between modules.
-
Dependencies:
- Unit — minimal, often using mocks.
- Integration — real dependencies and environment.
-
Speed:
- Unit — fast.
- Integration — slower.
Example of a unit test in Python using unittest:
import unittest
from mymodule import add
class TestAdd(unittest.TestCase):
def test_add_positive(self):
self.assertEqual(add(2, 3), 5)
if __name__ == '__main__':
unittest.main()
An integration test might, for example, verify that a function correctly writes data to a database and reads it back.