测试全类属性

Testing classwide attributes

假设我有一个名为 foo 的模块,带有 class BarBar 有一个 classwide 计数器属性,允许我跟踪创建实例的顺序。 foo 看起来像这样:

from itertools import count

class Bar:
    class_count = count(0)
    def __init__(self):
        self.id = self.class_count.next()

现在我有一个测试文件,我在其中测试 Bar 的各种功能。我不确定如何测试这个 id 属性,因为其他单元测试正在创建 Bar 的实例,所以我不知道 Bar 实例 [=23] 的给定 ID 是什么=]应该是。此外,我的 class 的这种行为意味着我的单元测试彼此独立,这是不可取的。我应该如何构建我的单元测试以使测试彼此独立?

您可以使用setUp to safe the current count and then temporarily reset the count. Then with tearDown您再次恢复原始状态:

from itertools import count
import unittest

class Bar:
    class_count = count(0)
    def __init__(self):
        self.id = next(self.class_count)


class TestBar(unittest.TestCase):
    def setUp(self):
        self.nxtcount = next(Bar.class_count)  # safe current state
        Bar.class_count = count(0)             # reset to 0

    def tearDown(self):
        Bar.class_count = count(self.nxtcount) # reset to old state

    def teststh1(self):
        x = Bar()
        self.assertEqual(x.id, 0)

    def teststh2(self):
        x1 = Bar()
        x2 = Bar()
        x3 = Bar()
        self.assertEqual(x1.id, 0)
        self.assertEqual(x2.id, 1)
        self.assertEqual(x3.id, 2)

这确保每个测试方法都以 Bar.class_count 0 开头。

我会去掉 Bar 以绕过构造函数。

class BarStub(Bar):
  def __init__(self):
    self.class_count = None
    self.id = None

现在你可以这样测试了:

class TestBar(...):
  def setUp(...)
    ...
    self.bar = BarStub()

  def test_foo_should_blah_when_blah(self):
    with mock.patch.object(self.bar, 'count_class', side_effect=[...]) as mock_count:
      actual = self.bar.unit_under_test(...)
      mock_count.assert_called_with([...])