Unittest vs Pytest Key Differences | Generated by AI

Home 2025.09

Here’s a crisp, no-table comparison focused on what actually changes in your day-to-day testing.

Philosophy & Style

Test Discovery

Assertions

Fixtures & Setup

Parametrization

Skips, Expected Failures, Markers

Plugins & Ecosystem

Mocks

Async Testing

Performance & Parallel

IDE/CI/Coverage

When to choose which

Interop & Migration

You can run unittest suites under pytest (pytest finds unittest.TestCases). This lets you migrate gradually:

  1. Start invoking pytest as the runner.
  2. Add pytest tests alongside existing ones.
  3. Introduce fixtures/parametrize where they help.
  4. Optionally refactor old TestCases to functions later.

Tiny side-by-side examples

The same test

unittest

import unittest

class TestMath(unittest.TestCase):
    def setUp(self):
        self.data = [1, 2, 3]

    def test_sum(self):
        self.assertEqual(sum(self.data), 6)

    def test_raises(self):
        with self.assertRaises(ZeroDivisionError):
            1 / 0

if __name__ == "__main__":
    unittest.main()

pytest

import pytest

@pytest.fixture
def data():
    return [1, 2, 3]

def test_sum(data):
    assert sum(data) == 6

def test_raises():
    with pytest.raises(ZeroDivisionError):
        1 / 0

Parametrization

unittest (subTest)

import unittest

class TestParity(unittest.TestCase):
    def test_even(self):
        for n in [0, 2, 4]:
            with self.subTest(n=n):
                self.assertEqual(n % 2, 0)

pytest

import pytest

@pytest.mark.parametrize("n", [0, 2, 4])
def test_even(n):
    assert n % 2 == 0

Mocking

unittest.mock

from unittest.mock import patch

@patch("pkg.api.fetch_user", return_value={"id": 1})
def test_uses_api(mock_fetch):
    from pkg.service import get_user
    assert get_user(1)["id"] == 1
    mock_fetch.assert_called_once_with(1)

pytest-mock

def test_uses_api(mocker):
    mock_fetch = mocker.patch("pkg.api.fetch_user", return_value={"id": 1})
    from pkg.service import get_user
    assert get_user(1)["id"] == 1
    mock_fetch.assert_called_once_with(1)

Practical recommendations

If you want, tell me your project layout and constraints (stdlib-only? need parallel? async? Django/Flask/FastAPI?) and I’ll sketch a minimal, opinionated test setup for you.


Back Donate