简体   繁体   English

如何在setUpClass中使python单元测试失败?

[英]How to fail a python unittest in setUpClass?

I am doing some unittests with python and some pre-test checks in setUpClass . 我正在使用python进行一些单元测试,并在setUpClass一些预测试。 How can I throw a unitest - fail within the setUpClass , as the following simple example: 我如何可以抛出一个unitest - fail的内setUpClass ,如下面的简单的例子:

class MyTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls):    
        unittest.TestCase.fail("Test")

    def test1(self):
        pass

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

gives the error TypeError: unbound method fail() must be called with TestCase instance as first argument (got str instance instead) . 给出错误TypeError: unbound method fail() must be called with TestCase instance as first argument (got str instance instead)

I understand the error I get as fail is a instance method, and I don't have an instance of MyClass yet. 我理解我得到的错误是失败是一个实例方法,我还没有MyClass的实例。 Using an instance on-the-fly like 像实时使用实例一样

unittest.TestCase().fail("Test")

also does not work, as unittest.TestCase itself has no tests. 也不起作用,因为unittest.TestCase本身没有测试。 Any ideas how to fail all tests in MyClass , when some condition in setUpClass is not met? 有什么想法,如果setUpClass某些条件,如何在MyClass失败所有测试?

Followup question: Is there a way to see the tests in setUpClass ? 后续问题:有没有办法在setUpClass查看测试?

self.fail("test") put into your setUp instance method fails all the tests 放入setUp实例方法的self.fail("test")失败所有测试

I think the easiest way to do this at the class level is to make a class variable so something like: 我认为在类级别执行此操作的最简单方法是创建类变量,如下所示:

@classmethod
def setUpClass(cls):
   cls.flag = False

def setUp(self):
   if self.flag:
       self.fail("conditions not met")

Hope this is what you want. 希望这是你想要的。

使用简单的断言应该有效

assert False, "I mean for this to fail"

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

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