Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn SetUp and TearDown in Unittest: Managing Test Environments | Mastering Unittest Framework
Quizzes & Challenges
Quizzes
Challenges
/
Python Structural Programming

bookSetUp and TearDown in Unittest: Managing Test Environments

The Four Phases of a Test:

  1. SetUp: prepare the environment. This might involve creating objects in the database, configuring system states like starting services or setting up database connections;
  2. Act: execute the function or methods to test;
  3. Assert: check and verify the outcomes against expected results;
  4. 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.

class Book:
    def __init__(self, title, author, amount):
        self.title = title
        self.author = author
        self.amount = amount

    def __repr__(self):
        return f"<Book {self.title}, written by {self.author}, {self.amount} pieces>"

    def sale(self):
        if self.amount > 0:
            self.amount -= 1
        else:
            return "This book sold out"

The next step, we'll define the test cases inside TestBook class.

import unittest

class 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.book

    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>")

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.

class TestBook(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        """This code will run before all tests"""
        print("Setting up the environment for all tests.")
        cls.book = Book("1984", "George Orwell", 2)

    @classmethod
    def 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.

Task

Swipe to start coding

Practice using setUp and tearDown methods in unittest by testing a Book class.

  • Define a test class named TestBook that inherits from unittest.TestCase.
  • Implement a setUp method that creates a Book instance with title '1984', author 'George Orwell', and amount 2. Assign it to self.book.
  • Implement a tearDown method that deletes the self.book instance.
  • Add a method named test_sale that:
    • Calls the sale method on self.book twice;
    • Asserts that the second call returns 'This book sold out'.
  • Add a method named test_book_repr that asserts the string representation of self.book is '<Book 1984, written by George Orwell, 2 pieces>'.
  • Use exactly these function names and class names for your tests to pass.

Solution

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 5. ChapterΒ 3
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Suggested prompts:

Can you explain the difference between setUp/tearDown and setUpClass/tearDownClass in more detail?

What happens if I don't use setUp or tearDown methods in my tests?

Can you show an example where setUpClass and tearDownClass are necessary?

close

bookSetUp and TearDown in Unittest: Managing Test Environments

Swipe to show menu

The Four Phases of a Test:

  1. SetUp: prepare the environment. This might involve creating objects in the database, configuring system states like starting services or setting up database connections;
  2. Act: execute the function or methods to test;
  3. Assert: check and verify the outcomes against expected results;
  4. 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.

class Book:
    def __init__(self, title, author, amount):
        self.title = title
        self.author = author
        self.amount = amount

    def __repr__(self):
        return f"<Book {self.title}, written by {self.author}, {self.amount} pieces>"

    def sale(self):
        if self.amount > 0:
            self.amount -= 1
        else:
            return "This book sold out"

The next step, we'll define the test cases inside TestBook class.

import unittest

class 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.book

    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>")

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.

class TestBook(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        """This code will run before all tests"""
        print("Setting up the environment for all tests.")
        cls.book = Book("1984", "George Orwell", 2)

    @classmethod
    def 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.

Task

Swipe to start coding

Practice using setUp and tearDown methods in unittest by testing a Book class.

  • Define a test class named TestBook that inherits from unittest.TestCase.
  • Implement a setUp method that creates a Book instance with title '1984', author 'George Orwell', and amount 2. Assign it to self.book.
  • Implement a tearDown method that deletes the self.book instance.
  • Add a method named test_sale that:
    • Calls the sale method on self.book twice;
    • Asserts that the second call returns 'This book sold out'.
  • Add a method named test_book_repr that asserts the string representation of self.book is '<Book 1984, written by George Orwell, 2 pieces>'.
  • Use exactly these function names and class names for your tests to pass.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 5. ChapterΒ 3
single

single

some-alt