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

如何用setUp方法解决Python测试用例中的NameError: name 'salary'未定义错误

问题:测试Employee类时触发NameError错误

我正在学习Eric Mathes的《Python Crash Course》,已经写好了Employee类,实例化运行没问题,但写测试用例时出现错误:NameError: name 'salary' is not defined。原以为在setUp方法里定义self.salary = salary能解决函数内变量无法外部调用的问题,结果还是报错,附上相关代码求帮忙。

Employee类代码

class Employee():
    """creates a ledger of employees"""

    def __init__(self, first, last, salary):
        """initalizes the atributes of the employee class"""
        self.first = first
        self.last = last
        self.salary = salary 
        msg = self.first.title() + " " + self.last.title() +\
         "." + " Salary: " + str(self.salary)
        print(msg)
        
    def give_raise(self, raises=5000):
        """increases employee salary by a defined amount"""
        
        self.salary += raises
        
        print(self.salary)

原测试用例代码

import unittest
from employee import Employee

class EmployeeTest(unittest.TestCase):
    """Test that class works"""
    
    def setUp(self):
        """Initialize an instance and attributes of the class"""
        self.employee_1 = Employee('kim', 'menace', 50000)
        self.salary = salary
        
        
    def test_give_default_raise(self):
        """tests that default raise is 5000"""
        self.employee_1.give_raise()
        
        self.assertEqual(raises, 5000)
        
unittest.main()

错误原因及修正方案

你的测试代码有两处明显问题:

  1. setUp方法里的self.salary = salary:右边的salary没有定义,你想获取的是员工实例的初始工资,应该从self.employee_1里取,改成self.original_salary = self.employee_1.salary。
  2. test_give_default_raise里的断言:raises是give_raise方法的参数,在测试方法里并没有定义这个变量。你要验证的是默认加薪后工资是否正确,应该断言员工当前工资等于初始工资+默认加薪额5000。

修正后的测试代码如下:

import unittest
from employee import Employee

class EmployeeTest(unittest.TestCase):
    """Test that class works"""
    
    def setUp(self):
        """Initialize an instance and attributes of the class"""
        self.employee_1 = Employee('kim', 'menace', 50000)
        self.original_salary = self.employee_1.salary  # 保存初始工资
        
    def test_give_default_raise(self):
        """tests that default raise is 5000"""
        self.employee_1.give_raise()
        # 断言加薪后工资等于初始工资+5000
        self.assertEqual(self.employee_1.salary, self.original_salary + 5000)
        
unittest.main()

这样修改后,测试就能正常运行,验证默认加薪功能是否正确了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:33:34