You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python单元测试断言错误:验证Lambda返回类型时出现异常

问题解决方法

错误原因分析

你的测试代码存在两个问题:

  • 测试方法的参数错误,TestCase的测试方法第一个参数必须是self,而非test_cases
  • 断言逻辑错误:type(func)返回的是函数类本身(<class 'function'>),而assertIsInstance是用来判断对象是否为某个类的实例,类本身不是自身的实例,因此会抛出断言错误

修正后的测试代码

from types import FunctionType
from unittest import TestCase

class Test(TestCase):
    def test_func(self):
        func = formatter(2)
        self.assertIsInstance(func, FunctionType)

额外验证方式

你也可以直接用callable()来验证返回值是可调用的函数:

self.assertTrue(callable(func))

内容的提问来源于stack exchange,提问作者dataviews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 04:06:25