为几个测试用例设置公共上下文的正确方法是什么?

时间:2012-11-18 16:01:31

标签: python unit-testing testcase test-suite

我正在使用unittest来测试我的终端互动实用程序。我有两个具有非常相似的上下文的测试用例:一个用于正确输出的测试,另一个用于在交互模式下正确处理用户命令。虽然,两种情况都模拟sys.stdout来抑制实际输出(输出也在交互工作过程中执行)。

请考虑以下事项:

class StdoutOutputTestCase(unittest.TestCase):
    """Tests whether the stuff is printed correctly."""

    def setUp(self):
        self.patcher_stdout = mock.patch('sys.stdout', StringIO())
        self.patcher_stdout.start()

    # Do testing

    def tearDown(self):
        self.patcher_stdout.stop()


class UserInteractionTestCase(unittest.TestCase):
    """Tests whether user input is handled correctly."""

    def setUp(self):
        self.patcher_stdout = mock.patch('sys.stdout', StringIO())
        self.patcher_stdout.start()

    # Do testing

    def tearDown(self):
        self.patcher_stdout.stop()      

我不喜欢的是,这里重复两次上下文设置(现在;可能会随着时间的推移而更多)。

有两种方法可以为这两种情况设置共同的上下文吗? unittest.TestSuite可以帮助我吗?如果有,怎么样?我找不到任何常见的上下文设置示例。

我还考虑过定义一个函数setup_common_context,它可以从两个案例的setUp调用,但它仍然是重复的。

1 个答案:

答案 0 :(得分:1)

我已经在我的项目中解决了这个问题,只需将常用的设置代码放在基类中,然后将测试用例放在派生类中。我的派生类setUp和tearDown方法只调用超类实现,并且只进行特定于这些测试用例的(de)初始化。另外,请记住,您可以在每个测试用例中放置多个测试,如果所有设置都相同,这可能是有意义的。

class MyBaseTestCase(unittest.TestCase):
    def setUp(self):
        self.patcher_stdout = mock.patch('sys.stdout', StringIO())
        self.patcher_stdout.start()

    # Do **nothing**

    def tearDown(self):
        self.patcher_stdout.stop()

class StdoutOutputTestCase(MyBaseTestCase):
    """Tests whether the stuff is printed correctly."""

    def setUp(self):
        super(StdoutOutputTestCase, self).setUp()

        # StdoutOutputTestCase specific set up code

    # Do testing

    def tearDown(self):
        super(StdoutOutputTestCase, self).tearDown()

        # StdoutOutputTestCase specific tear down code

class UserInteractionTestCase(MyBaseTestCase):
     # Same pattern as StdoutOutputTestCase
相关问题