我正在使用unittest
来测试我的终端交互式实用程序。我有 2 个上下文非常相似的测试用例:一个测试正确输出,另一个测试在交互模式下正确处理用户命令。虽然,这两种情况都模拟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
调用,但它仍然是重复的。
我已经在我的项目中解决了这个问题,只需将通用安装代码放在基类中,然后将测试用例放在派生类中。我的派生类 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