100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Unit Testing Best Practices Cheat Sheet

Unit Testing Best Practices Cheat Sheet

The Arrange-Act-Assert pattern, mocking external dependencies, parametrized tests, and the FIRST principles for writing reliable unit tests.

1 PageBeginnerApr 2, 2026

Arrange-Act-Assert

Structuring a pytest test into setup, action, and verification.

python
import pytestdef divide(a, b):    if b == 0:        raise ValueError("cannot divide by zero")    return a / bdef test_divide_returns_quotient():    # Arrange    a, b = 10, 2    # Act    result = divide(a, b)    # Assert    assert result == 5def test_divide_by_zero_raises():    with pytest.raises(ValueError, match="cannot divide by zero"):        divide(10, 0)

Mocking Dependencies

Isolating the unit under test with unittest.mock.

python
from unittest.mock import Mock, patchclass EmailService:    def send(self, to, body):        ...  # calls a real SMTP serverdef notify_user(email_service, user_email):    email_service.send(user_email, "Welcome!")    return Truedef test_notify_user_calls_send():    mock_service = Mock(spec=EmailService)    notify_user(mock_service, "a@example.com")    mock_service.send.assert_called_once_with("a@example.com", "Welcome!")@patch("mymodule.requests.get")   # patch where it's used, not where it's defineddef test_fetch_uses_requests_get(mock_get):    mock_get.return_value.status_code = 200    mock_get.return_value.json.return_value = {"ok": True}

Parametrized Tests

Running the same test logic against multiple input/output pairs.

python
import pytest@pytest.mark.parametrize("a, b, expected", [    (2, 3, 5),    (-1, 1, 0),    (0, 0, 0),])def test_add(a, b, expected):    assert a + b == expected

Testing Best Practices

Habits that keep a test suite fast, trustworthy, and maintainable.

  • FIRST principles- Tests should be Fast, Independent, Repeatable, Self-validating, and Timely
  • Descriptive names- Name tests after the behavior and expectation, e.g. test_returns_404_when_user_not_found
  • One behavior per test- Each test should verify a single behavior so failures pinpoint the exact problem
  • Avoid testing internals- Assert on observable outputs/behavior, not private implementation details, so refactors don't break tests
  • Mock external dependencies- Isolate the unit under test from databases, network calls, and the filesystem with test doubles
  • Use fixtures for setup- Share reusable setup/teardown code (e.g. pytest fixtures) instead of duplicating it in every test
  • Cover edge cases- Test empty inputs, boundary values, nulls, and error paths, not just the happy path
  • Keep tests deterministic- Avoid depending on real time, random values, network access, or execution order between tests
Pro Tip

If you find yourself mocking three or four collaborators just to test one function, treat that as a signal the function is doing too much — refactor it before writing more tests around it.

Was this cheat sheet helpful?

Explore Topics

#UnitTestingBestPractices#UnitTestingBestPracticesCheatSheet#Programming#Beginner#ArrangeActAssert#MockingDependencies#ParametrizedTests#TestingBestPractices#Testing#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet