问题描述
我正在使用 python 进行一些单元测试,并在 setUpClass
中进行一些预测试检查.如何在 setUpClass
中抛出 unitest
-fail
,如下面的简单示例:
I am doing some unittests with python and some pre-test checks in setUpClass
. How can I throw a unitest
-fail
within the setUpClass
, as the following simple example:
class MyTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
unittest.TestCase.fail("Test")
def test1(self):
pass
if __name__ == '__main__':
unittest.main()
给出错误TypeError: unbound method fail() must be called with TestCase instance as first argument (got str instance instead)
.
我明白我得到的错误是一个实例方法,我还没有 MyClass
的实例.即时使用实例,例如
I understand the error I get as fail is a instance method, and I don't have an instance of MyClass
yet. Using an instance on-the-fly like
unittest.TestCase().fail("Test")
也不起作用,因为 unittest.TestCase
本身没有测试.当 setUpClass
中的某些条件不满足时,如何使 MyClass
中的所有测试失败?
also does not work, as unittest.TestCase
itself has no tests. Any ideas how to fail all tests in MyClass
, when some condition in setUpClass
is not met?
后续问题:有没有办法查看setUpClass
中的测试?
Followup question: Is there a way to see the tests in setUpClass
?
推荐答案
self.fail("test")
放入你的 setUp 实例方法失败所有测试
self.fail("test")
put into your setUp instance method fails all the tests
我认为在类级别执行此操作的最简单方法是创建一个类变量,例如:
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")
希望这是你想要的.
这篇关于如何在setUpClass中使python单元测试失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!