Skip to content

Why Choose pytest over unittest?

Key differences

unittest

  • class-based (unittest.TestCaseunittest.TestCase)
  • assertion methods (self.assertEqualself.assertEqual)
  • more boilerplate

pytest

  • simple functions
  • plain assertassert
  • powerful fixtures
  • rich plugin ecosystem

Example comparison

unittest

test_add_unittest.py
import unittest
 
 
def add(a, b):
    return a + b
 
 
class TestAdd(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
test_add_unittest.py
import unittest
 
 
def add(a, b):
    return a + b
 
 
class TestAdd(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)

pytest

test_add_pytest.py
 
def add(a, b):
    return a + b
 
 
def test_add():
    assert add(2, 3) == 5
test_add_pytest.py
 
def add(a, b):
    return a + b
 
 
def test_add():
    assert add(2, 3) == 5

Why teams like pytest

  • less ceremony
  • clearer failures
  • fixtures scale better than setUp/tearDown
  • easy parameterization

๐Ÿงช Try It Yourself

Exercise 1 โ€“ Write a unittest TestCase

Exercise 2 โ€“ assertRaises

Exercise 3 โ€“ setUp and tearDown

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did