5 Tips to Improve Your Unit Tests in Python

Photo by Nick Fewings on Unsplash

1) @patch.object is your friend

from unittest.mock import patch@patch("folder1.folder2.file1.class1.func1")
def test_example(self, func1):
def test_example_2(self, func1):
from unittest.mock import patch
from folder1.folder2.file1 import class1
@patch.object(class1, "func1")
def test_example(self, func1):
@patch.object(class1, "func1")
def test_example_2(self, func1):

2) Avoid using global variables

def remove_from_list(name_list, name):
return name_list

def count_list(name_list):
return len(name_list)
names = ["Michael", "John"]class ExampleTests(TestCase):

def test_remove_from_list(self):
self.assertEqual(remove_from_list(names, "Michael"), ["John"])

def test_count_list(self):
self.assertEqual(count_list(names), 2)
FAILED tests/test_example.py::ExampleTests::test_count_list - AssertionError: 1 != 2
def get_names():
return ["Michael", "John"]

class ExampleTests(TestCase):

def test_remove_from_list(self):
self.assertEqual(remove_from_list(get_names(), "Michael"), ["John"])

def test_count_list(self):
self.assertEqual(count_list(get_names()), 2)
# from copy import copydef test_remove_from_list(self):
self.assertEqual(remove_from_list(copy(names), "Michael"), ["John"])

3) Get rid of unnecessary mock variables

@patch.object(class1, "func1", return_value=["abc"])
def test_example(self, mock_func1):
@patch.object(class1, "func1", Mock(return_value=["abc"]))
def test_example(self):

4) @patch.multiple is your friend

def test_example(self):
self.assertEqual("Michael", class1().get_name())
self.assertEqual(25, class1().get_age())

5) Faker is also your friend

names = [faker.name(), faker.name()]




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Scrum Masters can hunt in pairs!

Android Testing, Continuous Integration and Firebase

Time Machine Backups Too slow

Power BI for Business Users #01 — Architecture approaches to leverage the Power BI Service with a…

Boost Istio Service Mesh by upgrading to HTTP 2 — Part 1

Exop on StreamData

OOPS! Here comes the OOP.

Deploy PostgreSQL into IBM Cloud private

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


More from Medium

Factory Method Design Pattern in Python — Explained With Code

Python itertools Module Part 2

How to Write Clean Code (in Python) With SOLID Principles | Principle #4

How to write DRY code in Python using decorator functions! — Haseeb Kamal