Home > Blockchain >  Does Python unittest reset the setUp function in each call?
Does Python unittest reset the setUp function in each call?

Time:11-25

I am currently doing unit testing on a class

class Employee:
    """Class to define an employee"""

    def __init__(self, fname, lname, salary):
        self.fname = fname
        self.lname = lname 
        self.salary = salary 

    def give_raise(self, number=5000):
        self.salary  = number

I am writing tests that will test the methods I have defined in my class. The first will increase the employees salary by the default function parameter and the second a custom

from employee import Employee
import unittest

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

    def setUp(self):
        """
        Create employees and test the results
        """
        self.dave = Employee("dave", "stanton", 20000)

    def test_default_raise(self):
        self.dave.give_raise()
        self.assertEqual(25000, self.dave.salary)
        print(self.dave.salary)
        

    def test_custom_raise(self):
        self.dave.give_raise(10000)
        self.assertEqual(30000, self.dave.salary)
        print(self.dave.salary)


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

I am using a SetUp function to instantiate an instance of the employee class.

My question is does the value of self.dave.salary get reset to the base value on each method call?

30000
.25000
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s

I would expect the value of the second test to be 35000

CodePudding user response:

From the docs:

"The setUp() and tearDown() methods allow you to define instructions that will be executed before and after each test method."

  • Related