2016-02-19 37 views
-4

如果我通过执行accountant.give_default_raise()或accountant.give_custom_raise()来手动测试这两个函数,但一切正常,但当我运行单元测试时,它不断给我提供错误消息并说错误。代码有效,但单元测试说错误,发生了什么?

class Employee(): 

    def __init__(self, first_name, last_name, annual_salary = 3000): 
     """Declare the attributes""" 
     self.first_name = first_name 
     self.last_name = last_name 
     self.annual_salary = annual_salary 


    def give_default_raise(self): 
     """Add $5,0000 by default to the annual salary, but accept any amount""" 
     self.annual_salary += 5000 
     new_salary = self.annual_salary 
     print(new_salary) 

    def give_custom_raise(self): 
     """Add a custom amount""" 
     custom_raise = input("How much would you like to increase? ") 
     self.annual_salary += int(custom_raise) 
     new_custom_salary = self.annual_salary 
     print(new_custom_salary) 


accountant = Employee('John', 'Jones', 120000) 
accountant.give_default_raise() 

import unittest 

class TestEmployee(unittest.TestCase): 
    """Test the Employee class""" 

    def test_give_default_raise(self): 
     accountant = Employee('John', 'Jones', 120000) 
     self.assertEqual(annual_salary, 125000) 

unittest.main() 
+3

什么是'annual_salary'在'test_give_default_raise()'函数?该变量名似乎没有在任何地方定义。 –

+0

你有一个全局的'accountant',然后在'test_give_default_raise'中创建一个本地'accountant'。他们不提及同一个对象。 –

回答

4

我觉得你的测试功能应该是这样的:

def test_give_default_raise(self): 
    # create a new employee 
    accountant = Employee('John', 'Jones', 120000) 

    # give him a default raise 
    accountant.give_default_raise() 

    # verify that the salary was increased by the expected amount 
    self.assertEqual(accountant.annual_salary, 125000) 
0

我不认为你明白单元测试是如何工作的。你声称要测试该单元give_default_raise(),但从来没有打电话给它。

测试改为

def test_give_default_raise(self): 
    accountant = Employee('John', 'Jones', 120000) 
    accountant.give_default_raise() 
    self.assertEqual(annual_salary, 125000) 

此外,为了使give_custom_raise()单元测试,以及,你应该移动交互出来的,只是通过提高量的方法。

另外,看看setUp()tearDown()。在测试中覆盖班级的全部或大部分方法时,他们可以为您节省大量的工作。

+0

@idjaw:在打字时我敲了我的鼠标垫,答案很快就出来了。 ;) – jsfan

+0

当我看到您的扩展响应时,删除了我的评论。 :)干杯。 – idjaw