简体   繁体   中英

Setup method for nosetest. (Test class)

I am mocking out a database in some tests that I am doing. How would I create a setup method for the entire class, such that it runs each time an individual test within the class runs?

Example of what I am attempting to do.

from mocks import MockDB

class DBTests(unittest.TestCase):

    def setup(self):
        self.mock_db = MockDB()

    def test_one(self):
        #deal with self.mock_db

    def test_two(self):
        #deal with self.mock_db, as if nothing from test_one has happened

I'm assuming a teardown method would also be possible, but I can't find documentation that will do something like this.

If you are using Python unit test framework something like this is what you want:

class Test(unittest.TestCase):


    def setUp(self):
        self.mock_db = MockDB()

    def tearDown(self):
        pass  # clean up 

    def test_1(self):
        pass  # test stuff

Documentation

With Nose, subclassing of TestCase works the same way as standard unittest -- setUp / tearDown are the same. From the nose docs

Test classes

A test class is a class defined in a test module that matches testMatch or is a subclass of unittest.TestCase. All test classes are run the same way: Methods in the class that match testMatch are discovered, and a test case is constructed to run each method with a fresh instance of the test class. Like unittest.TestCase subclasses, other test classes can define setUp and tearDown methods that will be run before and after each test method. Test classes that do not descend from unittest.TestCase may also include generator methods and class-level fixtures. Class-level setup fixtures may be named setup_class, setupClass, setUpClass, setupAll or setUpAll; teardown fixtures may be named teardown_class, teardownClass, tearDownClass, teardownAll or tearDownAll. Class-level setup and teardown fixtures must be class methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM