简体   繁体   English

单元测试 setUpClass 不起作用

[英]Unittest setUpClass not working

I am trying to get started with unittest, but I am having a problem getting setUpClass() to work.我正在尝试开始使用 unittest,但是在让setUpClass()工作时遇到问题。 Here is my test code...这是我的测试代码...

import unittest

class TestRepGen(unittest.TestCase):
    """ Contains methods for training data testing """

    testvar = 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() .显示断言错误消息,表明self.testvar == None ,并且没有被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.如果我从 IDE (Wing) 或直接从命令行运行代码,我会得到相同的结果。 For the record, I am using Python 3.2.1 under Windows7.作为记录,我在 Windows7 下使用 Python 3.2.1。

setUpClass is new to the unittest framework as of 2.7 and 3.2.从 2.7 和 3.2 开始,setUpClass 是 unittest 框架的新功能。 If you want to use it with an older version you will need to use nose as your test runner instead of unittest.如果您想将它与旧版本一起使用,您将需要使用鼻子作为测试运行程序而不是 unittest。

I'm going to guess you aren't calling this test class directly, but a derived class.我猜你不会直接调用这个测试 class,而是一个派生的 class。

If that's the case, you have to call up to setUpClass() manually -- it's not automatically called.如果是这种情况,您必须手动调用setUpClass() - 它不会自动调用。

class TestB(TestRepGen):
    @classmethod
    def setUpClass(cls):
        super(TestB, cls).setUpClass()

Also, accoding tothe docs class-level fixtures are implemented by the test suite .此外,测试套件实现了对文档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.因此,如果您以某种未发布的奇怪方式调用TestRepGentest_methodsetUpClass可能无法运行。

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.当我应该(并且认为我是)使用 3.2.1 时,我正在使用 3.1.2。 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:-( ).非常感谢所有回复的人(很抱歉浪费您的时间:-()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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