如何为多个测试用例设置共同的上下文?

2024-06-16 11:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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调用的,但它仍然是重复的。在


Tags: selfisdefstdoutsyssetup情况tests
1条回答
网友
1楼 · 发布于 2024-06-16 11:30:08

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

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

相关问题 更多 >