在unittest中的测试之间是否存在变量变化?
如何在unitttest中持久保留从TestCase
继承的同一对象内所做的更改?
How do I persist changes made within the same object inheriting from TestCase
in unitttest?
from unittest import TestCase, main as unittest_main
class TestSimpleFoo(TestCase):
foo = 'bar'
def setUp(self):
pass
def test_a(self):
self.assertEqual(self.foo, 'bar')
self.foo = 'can'
def test_f(self):
self.assertEqual(self.foo, 'can')
if __name__ == '__main__':
unittest_main()
即:我希望以上两项测试通过
I.e.: I want those two tests above to pass
正如一些评论所言,以这种方式构造测试可能是测试本身的设计缺陷,您应该考虑对其进行重组.但是,如果您要执行此操作,并且依赖于所使用的测试运行程序以字母(看似)顺序执行它们的事实,那么我建议以下内容.
As some comments have echoed, structuring your tests in this manner is probably a design flaw in the tests themselves and you should consider restructuring them. However, if you want to do this and rely on the fact that the test runner you are using executes them in an alphabetical (seemingly) order then I suggest the following.
类似于@Matthias所说的,但是对于以后您可能决定从该类继承的情况,我会做另一件事.
Similar to what @Matthias was saying but I would do one thing differently for the cases where you may decide to inherit from the class at a later date.
from unittest import TestCase, main as unittest_main
class TestSimpleFoo(TestCase):
foo = 'bar'
def setUp(self):
pass
def test_a(self):
self.assertEqual(self.__class__.foo, 'bar')
self.__class__.foo = 'can'
def test_f(self):
self.assertEqual(self.__class__.foo, 'can')
if __name__ == '__main__':
unittest_main()
此答案与您接受的@Matthias答案之间的区别是该类的显式声明与该类引用的查找.
The difference between this answer and @Matthias's answer you accepted is the explicit declaration of the class versus the lookup of said class reference.
TestSimpleFoo vs self.__class__
我更喜欢动态性,因此我可以稍后继承测试,并背对背运行两个测试类,并且两者之间没有任何交叉.因为如果您选择从此类继承,则显式命名类引用将导致两个测试类都针对该引用而不是它们各自的类运行.
I prefer the dynamicness so I can inherit the tests later and run both test classes back to back and not have any cross over between the two. Because if you would choose to inherit from this class, explicitly naming the class reference would cause both test classes to run against that reference rather than their own respective classes.