I am trying to get started with unittest, but I am having a problem getting setUpClass()
to work. Here is my test code...
import unittest
class TestRepGen(unittest.TestCase):
""" Contains methods for training data testing """
te开发者_StackOverflowstvar = None
@classmethod
def setUpClass(cls):
cls.testvar = 6
def test_method(self):
""" Ensure data is selected """
self.assertIsNotNone(self.testvar,"self.testvar is None!")
# run tests
if __name__ == '__main__':
unittest.main()
The assert error message is displayed, indicating that self.testvar == None
, and has not been changed by setUpClass()
. Is there something wrong with my code?
I get the same result if I run the code from within my IDE (Wing), or directly from the command line. For the record, I am using Python 3.2.1 under Windows7.
setUpClass is new to the unittest framework as of 2.7 and 3.2. If you want to use it with an older version you will need to use nose as your test runner instead of unittest.
I'm going to guess you aren't calling this test class directly, but a derived class.
If that's the case, you have to call up to setUpClass()
manually -- it's not automatically called.
class TestB(TestRepGen):
@classmethod
def setUpClass(cls):
super(TestB, cls).setUpClass()
Also, accoding to the docs class-level fixtures are implemented by the test suite
. So, if you're calling TestRepGen
or test_method
some weird way you didn't post, setUpClass
might not get run.
Ok - it's hands-up time to admit that it was my mistake. I was using 3.1.2 when I should have been (and thought I was) using 3.2.1. I have now changed to the correct version, all is well and the test is passing. Many thanks to all who replied (and sorry for wasting your time :-( ).
精彩评论