2

When running a simple unittest it would sometimes be easier to be able to keep the tests inside the class. However, I don't know how to reload the current module, and so whenever that's needed I have to move the tests into a separate module. Is there a way around this?

module: foo
import unittest

class MyObject
...

class MockMyObject
...

class TestMock(unittest.TestCase):

    def setUp(self):
        MyObject = MockMyObject
        mocked = MyObject()

    def tearDown(self):
        reload(foo) # what goes here?

    def testFunction(self):
        mocked.do_mocked_function()

if __name__ == "__main__":
    unittest.main()

The way I've found to handle this is to import sys and reload(sys.modules[__name__]) in the tearDown method, but I'm wondering if there is a better method.

2 Answers 2

2

You can save your original class in a variable and restore it in the tearDown function.
Here is an example:

class TestMock(unittest.TestCase):

    original = MyObject

    def setUp(self):
        global MyObject
        MyObject = MockMyObject

    def tearDown(self):
        global MyObject
        MyObject = TestMock.original

    def testFunction(self):
        MyObject().do_mocked_function()
Sign up to request clarification or add additional context in comments.

1 Comment

That's great, thanks. And for pointing out the global part.
1

that's not a good idea to reload your module.

class TestMock(unittest.TestCase):

def setUp(self):
    MyObject = MockMyObject
    self.mocked = MyObject()

def tearDown(self):
    pass

def testFunction(self):
    self.mocked.do_mocked_function()

2 Comments

In this case the tearDown method isn't doing anything. And if I have more than one test then any patched changes to MockMyObject will persist between them which is what I'm trying to avoid by with reload.
every test case will execute the setUp method firstly, then there will be a brand new self.mocked object of MyObject.

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.