小编Don*_*Don的帖子

单元测试如何/为何在测试用例中相互影响以及如何防止这种行为?

我正在为一个用 Python3.6/Django 2.0 制作的 web 应用程序编写测试,我有以下情况:

class TestFoo(TestCase):
    def test_a(self):
        obj = Foo.objects.create(a = "bar")
        expectation = {"a" : "bar"}
        self.assertEquals(obj.method_x(), expectation)

    def test_b(self):
        obj = Foo.objects.create(a = "baz")
        expectation = {"a" : "baz"}
        self.assertEquals(obj.method_x(), expectation)

    def test_c(self):
        obj = Foo.objects.create(a = "bar")
        obj2 = Foo.objects.create(a = "baz")
        obj.b.add(obj2)
        expectation = {"a" : "bar", "b" : {"a": "baz"}}
        self.assertEquals(obj.method_x(), expectation)
Run Code Online (Sandbox Code Playgroud)

据我了解,每个测试都是单独运行的,但是当我与测试 a 或 b 一起运行 test_c 时,所有测试都会失败。基本上是这样的:

  • test_a + test_b + test_c =全部失败
  • 测试_a + 测试_b =全部通过
  • test_c …

django unit-testing python-3.x django-unittest

6
推荐指数
1
解决办法
1327
查看次数