【问题标题】:DRY in Unit Test for PythonPython 单元测试中的 DRY
【发布时间】:2015-10-02 01:41:05
【问题描述】:

从两个文件test_now.py和test_later.py如下:

# test_now.py
import unittest

class CommonClass(unittest.TestCase):
    def hello(self):
        print "Hello there"
    def bye(self):
        print "Bye"
    def seeYouAgain(self):
        print "See You Again"
    def whatsUp(self):
        print "What's up?"

    def testNow(self):
        self.hello()
        self.bye()

if __name__ == '__main__':
    unittest.main()
# test_later.py
import unittest

class CommonClass(unittest.TestCase):
    def hello(self):
        print "Hello there"
    def bye(self):
        print "Bye"
    def seeYouAgain(self):
        print "See You Again"
    def whatsUp(self):
        print "What's up?"

    def testLater(self):
        self.hello()
        self.whatsUp()

if __name__ == '__main__':
    unittest.main()

我整理成三个文件如下:

# common_class.py
import unittest

class CommonClass(unittest.TestCase):
    def hello(self):
        print "Hello there"
    def bye(self):
        print "Bye"
    def seeYouAgain(self):
        print "See You Again"
    def whatsUp(self):
        print "What's up?"  
# test_now.py
from common_class import *
def testNow(self)
    self.hello()
    self.bye()
setattr(CommonClass, 'testNow', testNow)

if __name__ == '__main__':
    unittest.main()
# test_later.py
from common_class import *
def testLater(self):
    self.hello()
    self.whatsUp()
setattr(CommonClass, 'testLater', testLater)

if __name__ == '__main__':
    unittest.main()

这种 DRY 方法有哪些顾虑?

【问题讨论】:

  • 你能修正一下格式吗?
  • 不幸的是,将模块级函数添加为类的方法比这要复杂一些
  • 您的 TestCase 测试什么?没有什么。你为什么不try reading the documentation for unittest

标签: python unit-testing dry


【解决方案1】:

在导入模块时修改其他模块是一个巨大的缺陷。

相反,创建子类:

# test_now.py
from common_class import CommonClass

class TestNow(CommonClass):
    def testNow(self)
        self.hello()
        self.bye()
# test_later.py
from common_class import CommonClass
class TestLater(CommonClass):
    def testLater(self):
        self.hello()
        self.whatsUp()

或者您可以将函数移出类,因为它们不依赖于 self 中的任何内容。

或者,一旦你的问题超出了琐碎的例子,可能会放弃使用标准的 unittest 框架并使用像 py.test 这样更理智的东西,这样你就可以使用适当的固定装置和各种东西。

【讨论】:

  • 我已经简化了 CommonClass 以突出 DRY 上的问题。事实上,Django 框架中的那些 setUp(self) 和 tearDown(self) 更复杂。真正的测试文件测试由 Django 创建的基于 Web 的应用程序。
猜你喜欢
  • 1970-01-01
  • 2015-11-18
  • 2015-11-30
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
相关资源
最近更新 更多