gpt4 book ai didi

python - 如何对 unittest 测试用例进行单元测试

转载 作者:行者123 更新时间:2023-11-28 16:50:25 25 4
gpt4 key购买 nike

我有一个 unittest.TestCase 子项,它定义了几个特定于域的断言检查。我想运行一些单元测试来对该功能进行单元测试,以控制 future 更新中的一切工作。

class MyBaseTestCase(unittest.TestCase):
def setUp(self):
...
def tearDown(self):
...
def run(self, result):
...
def assertSpec(self, condition, message):
...

我想在其他单元测试中实例化 MyBaseTestCase,像这样:

class TestBase(unittest.TestCase):
def test_assertSpec(self):
self.testclass = MyBaseTestCase()
self.assertRaises(AssertionError, self.testclass.assertSpec, False)

我在执行此操作时遇到了多个不同的错误,所以我的问题是单元测试自定义单元测试函数的常见做法是什么?

如果有帮助:

$ jython
>>> import sys
>>> sys.version
'2.5.2 (Release_2_5_2:7206, Mar 2 2011, 23:12:06) \n[Java HotSpot(TM) Server VM (Sun Microsystems Inc.)]'

最佳答案

不确定是否有任何特定于 Jython 的东西会破坏它,但我会这样做:

import StringIO
import unittest


# The TestCase subclass to test
class MyBaseTestCase(unittest.TestCase):
def assertSpec(self, thing):
assert thing == 123


# The testcase for MyBaseTestCase
class TestMyTest(unittest.TestCase):
def test_assetSpec(self):
"""Ensure assertSpec works
"""

class _TestSpec(MyBaseTestCase):
def test_failure_case(self):
self.assertSpec(121)
def test_success_case(self):
self.assertSpec(123)

# Load tests from _TestSpec
loader = unittest.TestLoader()
suite = loader.loadTestsFromTestCase(_TestSpec)

# Create runner, and run _TestSpec
io = StringIO.StringIO()
runner = unittest.TextTestRunner(stream = io)
results = runner.run(suite)

# Should be one failed test, and one passed test
self.assertEquals(results.testsRun, 2)
self.assertEquals(len(results.failures), 1)

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

关于python - 如何对 unittest 测试用例进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8308435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com