unittest test class code instance for python

  • 2020-06-15 09:25:53
  • OfStack

The nittest unit test framework can be applied not only to unit tests, but also to the development and execution of WEB automated test cases, which can organize the execution of test cases and provide rich assertion methods to determine whether the test cases pass and ultimately generate test results. Today I'll summarize how to use the unittest unit testing framework for WEB automated testing.

Topic:

Write a class named Employee with the method ___, with the first, last, and annual salary, and store them all in the attributes. Write a method called give_raise(), which increases the annual salary by $5,000 by default, but can also accept other annual salary increases.

Write a test case for Employee with two test methods: test_give_default_raise() and test_give_custom_raise(). Use method setUp() to avoid creating a new employee instance in each test method. Run the test case to make sure both tests pass.


employ.py 
 Class to be tested  
 class Employee(): 
  def __init__(self,first_name,last_name,salary): 
    self.first_name=first_name 
    self.last_name=last_name 
    self.salary=salary 
  def give_raise(self,default=5000): 
    return int(self.salary)+default 

test_employ.py 
 The test class   
# coding=utf-8 
import unittest 
from employ import Employee  
class TestEmploy(unittest.TestCase): 
  def setUp(self): 
    self.people=Employee("ZHU","Fangya",20000) 
    self.salary=[25000,30000] 
  def test_give_default_raise(self): 
    self.assertEqual(self.people.give_raise(),self.salary[0])  
  def test_give_custome_raise(self): 
    self.default=10000 
    self.assertEqual(self.people.give_raise(default=10000),self.salary[1])   
if __name__=="__main__": 
  unittest.main() 

The results


Done:2 of 2 (0.137s) 
C:\Python27\python.exe "C:\Program Files (x86)\JetBrains\PyCharm 4.0.6\helpers\pycharm\utrunner.py" C:\Users\waiwai\PycharmProjects\untitled2\test_employ.py true 
Testing started at 16:03 ... 
 
Process finished with exit code 0 

conclusion

That's the end of this article on python's unittest test class code example, and I hope you found it helpful. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: