SetUp and TearDown in Unittest: Managing Test Environments
The Four Phases of a Test:
- SetUp: prepare the environment. This might involve creating objects in the database, configuring system states like starting services or setting up database connections;
- Act: execute the function or methods to test;
- Assert: check and verify the outcomes against expected results;
- TearDown: clean up after each test. This ensures that any changes to the environment do not affect subsequent tests.
SetUp and tearDown are optional phases.
Implementing SetUp and TearDown
The setUp and tearDown methods in Unittest are instance methods called before and after each test method, respectively.
Let's consider a Book
class with a custom __repr__
and sale
methods.
pythonclass Book:def __init__(self, title, author, amount):self.title = titleself.author = authorself.amount = amountdef __repr__(self):return f"<Book {self.title}, written by {self.author}, {self.amount} pieces>"def sale(self):if self.amount > 0:self.amount -= 1else:return "This book sold out"
The next step, we'll define the test cases inside TestBook
class.
pythonimport unittestclass TestBook(unittest.TestCase):def setUp(self):print("Setting up the environment for each test.")self.book = Book("1984", "George Orwell", 2)def tearDown(self):print("Cleaning up after each test.")del self.bookdef test_sale(self):self.book.sale()assert self.book.sale() == "This book sold out"def test_book_repr(self):self.assertEqual(repr(self.book), "<Book 1984, written by George Orwell, 2 pieces>")
After the test_sale
case passed, the number of books was reset to the original value for the test_book_repr
because the setUp method runs before each test.
SetUp and tearDown at the method level ensure that each test runs in a clean environment, making tests predictable and independent.
Implementing SetUpClass and TearDownClass
These are class methods that run once for the whole class, at the beginning and end of the test suite.
pythonclass TestBook(unittest.TestCase):@classmethoddef setUpClass(cls):"""This code will run before all tests"""print("Setting up the environment for all tests.")cls.book = Book("1984", "George Orwell", 2)@classmethoddef tearDownClass(cls):"""This code will run after all tests"""print("Cleaning up after all tests.")def test_sale(self):self.book.sale()assert self.book.sale() == "This book sold out"def test_book_repr(self):self.assertEqual(repr(self.book), "<Book 1984, written by George Orwell, 2 pieces>")# An AssertionError will occur because the amount was changed in the# 'test_sale' and the book was not updated prior to this test.
SetUp and tearDown at the class level reduce the overhead of preparing and cleaning up resources that are expensive to create and destroy.
Bedankt voor je feedback!