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

Python单元测试:如何测试含if-else逻辑函数的else分支?

调整方案

第一步 修复原有代码的基础问题

  • 原func_test函数内部硬编码了indicator = True,没有预留入参,无法从外部控制分支走向,需要新增indicator作为函数入参
  • 原TestJob类定义末尾缺少冒号,属于基础语法错误,需要补全
  • 原测试将函数调用结果写为类固定属性,仅会在类加载时执行一次,无法覆盖多场景测试需求,需要调整为在测试方法内单独调用函数

第二步 新增else分支测试用例

优化断言逻辑,放弃模糊的assertGreater判断,直接匹配分支预期返回值,确保逻辑正确性:if分支预期返回5+10=15,else分支预期返回6*10=60。


调整后完整可运行代码

import unittest

def func_test(indicator: bool = True):
    if indicator == True:
        a = 5
        b = 10
        total = a + b
        return total
    else:
        a = 6
        b = 10
        total = a * b
        return total


class TestJob(unittest.TestCase):
    # 验证if分支逻辑
    def test_func_test_if_branch(self):
        total = func_test(indicator=True)
        self.assertEqual(total, 15)
    
    # 验证else分支逻辑
    def test_func_test_else_branch(self):
        total = func_test(indicator=False)
        self.assertEqual(total, 60)

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

调整后执行单元测试会同时覆盖两个分支,任意分支逻辑出错都会直接抛出断言失败提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:36:04