单元测试框架处理多组数据的另一种写法:基于构造函数和超继承

众所周知,在单元测试框架中引入ddt,可以将一组数据分解为多组数据,从而实现一条数据对应一个测试用例。但是除此之外,有没有别的办法来实现这个目的呢?

1|0一. 代码部分


1. 创建一个被测函数math_method.py

class MethMethod(): def add_test(self,a,b): return (a+b)

2. 创建测试用例test_math_method.py

import unittest from homework.math_method import MethMethod #测试类 class TestMathMethod(unittest.TestCase): def __init__(self, methodName, a, b, expected): super(TestMethMethod, self).__init__(methodName) self.a = a self.b = b self.expected = expected #测试用例 def test_add(self): try: self.assertEqual(result, self.expected) except Exception: print("出错了") else: print("计算结果是:{}".format(result))

3. 创建测试数据test_data.txt

[{"a":2,"b":3,"expected":5},{"a":-1,"b":-2,"expected":-3},{"a":3,"b":-1,"expected":-2},{"a":-3,"b":-1,"expected":-4}]

4. 创建测试集test_suite.py

import unittest from homework.test_math_method import TestMathMethod import HTMLTestRunnerNew fs= open("test_data.txt") datas = fs.read() datas = eval(datas) print(type(datas)) if __name__ == '__main__': suite=unittest.TestSuite() for item in datas: suite.addTest(TestMathMethod("test_add", item['a'], item['b'], item['expected'])) file=open("test_report.html","wb+") runner=HTMLTestRunnerNew.HTMLTestRunner(file,title="加法单元测试报告",tester="july") runner.run(suite)

2|0二. 代码分析


1. 测试用例类中需要定义一个构造函数,这个构造函数继承了父类的属性,也就是unittest.TestCase的methodName参数

同时,在子类中也重写了构造函数,添加了参数a, b, expected,而这三个则是测试用例函数test_add需要用到的

class TestMethMethod(unittest.TestCase): def __init__(self, methodName, a, b, expected): super(TestMethMethod, self).__init__(methodName) self.a = a self.b = b self.expected = expected

请看TestCase的源码

class TestCase(object):

failureException = AssertionError longMessage = True maxDiff = 80*8 # If a string is longer than _diffThreshold, use normal comparison instead # of difflib. See #11763. _diffThreshold = 2**16 # Attribute used by TestSuite for classSetUp _classSetupFailed = False def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. """ self._testMethodName = methodName self._outcome = None self._testMethodDoc = 'No test' try: testMethod = getattr(self, methodName) except AttributeError: if methodName != 'runTest': # we allow instantiation with no explicit method name # but not an *incorrect* or missing method name raise ValueError("no such test method in %s: %s" % (self.__class__, methodName)) else: self._testMethodDoc = testMethod.__doc__ self._cleanups = [] self._subtest = None

2. 此时回到测试集中,看下面一段,TestMathMethod类中本来只有一个参数,methodName,也就是测试用例名,但此时的TestMathMethod已经被我们改写了:不仅继承了父类的methodName方法,而且构造函数中新增了三个参数a, b, expected,这样我们在收集测试用例时,可以为TestMathMethod类添加四个参数:methodName, a, b, expected。通过for循环遍历一组数据,这样可以将多组数据作为多个测试用例添加到测试集中

for item in datas: suite.addTest(TestMathMethod("test_add", item['a'], item['b'], item['expected']))

3|0三. 比较


ddt的方法:简单,因为涉及到装饰器,不易理解

构造函数:略显繁琐,但容易理解

 


__EOF__

本文作者cnhkzyy
本文链接https://www.cnblogs.com/my_captain/p/9508358.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   cnhkzyy  阅读(558)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示