python - 将 var 传递给 Python 单元测试 TestCase 和/或 TestSuite 的正确方法是什么?

标签 python unit-testing

我需要针对多个 REST 后端资源运行 Python 单元测试测试套件,因此我需要将 Resource 对象传递给测试套件和各个测试用例。

设置全局变量是执行此操作的正确方法,还是有更好的方法?

资源 = 资源('http://example.com')

class RestTestCase(unittest.TestCase):
    def setUp(self):
        self.resource = resource

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(RestTestCase))
    return suite

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

最佳答案

遵循标准库如何编写自己的单元测试的示例。将资源放入类变量中并使用继承来测试各种资源:

class RestTestCase(unittest.TestCase):
    resource = Resource('http://example.com')

    def sometest(self):
        r = self.resource
        ...
        self.assertEqual(expectedresult, actualresult)

class SomeOtherRestTestCase(RestTestCase):
    resource = Resource('http://someother.example.com')

class YetAnotherRestTestCase(RestTestCase):
    resource = Resource('http://yetanother.example.com')

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

关于python - 将 var 传递给 Python 单元测试 TestCase 和/或 TestSuite 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8276310/

相关文章:

python - 使用 Numpy 生成 N 维矩阵

python - 谷歌应用引擎 : Database object is not iterable

unit-testing - 如何在 Kotlin 上测试数据类?

sql-server - 我如何知道 SQL 全文索引填充何时完成?

Python:在异常时返回空值

python - 你如何在不知道错误的情况下断言两个函数抛出相同的错误?

c# - 在这种情况下编写好的单元测试

java - jmockit 捕获模拟方法参数

unit-testing - 我应该测试私有(private)/ protected 方法吗?为什么?

python - 骰子游戏分数和开始不起作用