代码工作,但单元测试说错误,发生了什么?

时间:2016-02-19 21:29:44

标签: python unit-testing python-3.x

如果我通过执行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()

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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()。通过测试覆盖全班或大部分课程时,它们可以为您节省大量的工作。