Senior
How was the problem of code duplication in tests solved?
sobes.tech AI
Answer from AI
Several approaches are used to solve the problem of code duplication in tests:
- Extracting common functions and methods: repetitive actions are moved into separate helper functions or methods, which are then called from different tests.
- Using design patterns: for example, the Page Object pattern in UI tests helps encapsulate interaction with interface elements, reducing duplication.
- Test parameterization: allows running the same test with different input data, avoiding code copying.
- Configuring fixtures and setup/teardown methods: common preparation and cleanup of data are performed centrally.
An example in Python using pytest and parameterization:
import pytest
def add(a, b):
return a + b
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(5, 7, 12),
(0, 0, 0),
])
def test_add(a, b, expected):
assert add(a, b) == expected
This approach reduces the amount of repetitive code and makes test maintenance easier.