python - 如何对具有两个返回值的函数进行单元测试?
问题描述
我在一个类中有一个函数,它返回两个字典。
class A():
def __init__(self):
self.dict1={}
self.dict2={}
def funct1(self,a,b):
self.dict1['a']=a
self.dict2['b']=b
return self.dict1,self.dict2
我想编写一个单元测试来测试返回两个字典的函数funct1
解决方案
Python 函数只返回一个对象,always。在您的情况下,该对象是一个包含两个对象的元组。
只需测试这两个对象;您可以在作业中解压缩它们并测试各个字典,例如:
def test_func1_single(self):
instance_under_test = A()
d1, d2 = instance_under_test.func1(42, 81)
self.assertEqual(d1, {'a': 42})
self.assertEqual(d2, {'b': 81})
def test_func1_(self):
instance_under_test = A()
d1, d2 = instance_under_test.func1(42, 81)
self.assertEqual(d1, {'a': 42})
self.assertEqual(d2, {'b': 81})
d3, d4 = instance_under_test.func1(123, 321)
# these are still the same dictionary objects
self.assertIs(d3, d1)
self.assertIs(d4, d2)
# but the values have changed
self.assertEqual(d1, {'a': 123})
self.assertEqual(d2, {'b': 321})
您测试的确切内容取决于您的特定用例和要求。
推荐阅读
- java - Spring - Neo4j:当存在关系实体时,类属性返回 Null
- javascript - 使用变量(名称)将数组推送到变量(数组)
- jquery - 如何将活动链接添加到引导程序 4 垂直菜单
- python - 在 Python 中导入库时出现分段错误
- python - 使用基于主机的身份验证没有密码的 Paramiko ssh
- node.js - Comodo SSL 证书捆绑安装 Node.js / Express
- python - TypeError:“模块”对象在 Django 中不可调用
- php - 将 url 中的 %20 替换为 "_" .htaccess
- r - 如何使用 gsub 将 's 替换为 's 仅用于数据集的一列?
- python - 如何将烧瓶默认 http 方法从 GET 更改为 POST