3

I have a discrepancy in understand of the basic unittest methods in python. Given this test file below:

import unittest, sys


class TestStringMethods(unittest.TestCase):

    def setUp(self):
        self.mystring = "example string"

    def tearDown(self):
        del self.mystring

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        with self.assertRaises(TypeError):
            s.split(2)

My understanding based on what I've read ("Methods named setUp in a TestCase are run, automatically, before every test method.", http://gettingstartedwithdjango.com/en/lessons/testing-microblog/#toc1, etc) I interpret the order of events like:

1. set up self.mystring
2. run test_upper
3. tear down self.mystring

4. set up self.mystring
5. run test_isupper
6. tear down self.mystring

7. set up self.mystring
8. run test_split
9. tear down self.mystring

My co-workers interpret the docs as saying unittest works as follows:

1. set up self.mystring
2. run test_upper
3. run test_isupper
4. run test_split
5. tear down self.mystring

this is a pretty important distinction, which one is right?

3 Answers 3

4

You're right. The setup and teardown methods are run before and after each test case. This ensures that each test is run in isolation, so the order of tests doesn't matter. Objects created during setup that are changed during one test are re-created for each test, so the tests don't effect each other.

Sign up to request clarification or add additional context in comments.

Comments

4

Python Unittest Docs

You are right about setUp and tearDown, they run before and after each test method within that class. But your co-workers may have been thinking of setUpClass and tearDownClass, those would run once before any test methods in the class were executed and after all the test methods were done, respectively.

Comments

2

the methods setUpClass/tearDownClass can be used if you need to set up something once before all cases and tear it down after all cases. Most of the time though, you want the behavior you described so that the unit tests do not interfere with one another or depend on one another.

1 Comment

so the default behavior is the list 1-9, how do you change the order to sandwich all your tests in the middle like the 1-5 list? I'm assuming setUpClass()... A class method called before tests in an individual class run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.