How to Write Unit Test in Python?
Unit tests are written in order to test a specific piece of code and make sure that the code is working the way we want. A unit test will verify that your code is working and that the code inputs and outputs are as intended.
Python has a built-in support for unit testing. The Python unittesting framework was originally inspired by JUnit and has a similar flavor to major unit testing frameworks in other languages. It supports automation of tests, sharing of configuration and stop code for tests, aggregation of tests in collections, and independence of tests with respect to the reporting framework.
The Python unittest framework supports the following important concepts in an object-oriented way:
- test fixture - A test fixture is the preparation required for one or more tests, and all related cleaning actions. These can include, for example, creating temporary or proxy databases, directories, or starting a server process.
- test case - A test case is a single test unit that verifies a specific response to a particular set of inputs. The unittest framework provides a core class, TestCase, which can be used for creating new test cases.
- test suite - A test suite is used to group the tests that have to be run together. It is a collection of test cases, test suites or both.
- test runner - A test runner is a component that manages tests and provides the result to the user. The runner can use a GUI, a text interface, or return a special value to indicate the test results.
Here is a simple program to test two functions:
def sum(a, b):
return a + b
def minus(a, b):
return a - b
self.a = 104
self.b = 240
print("test sum called")
result = sum(self.a, self.b)
print("test minus called")
result = minus(self.a, self.b)
self.a = 0
self.b = 0
if __name__ == "__main__":
test minus called
test sum called
Ran 2 tests in 0.000s
The above example is explained below:
- We started by creating a testcase class (CalculatorTestCase) by subclassing unittest.TestCase.
- The two individual tests methods whose names start with the letters test informs the test runner about which methods represent tests.
- The setUp() method is used to set up the test fixture and is executed before any test method is run.
- The tearDown() method is used to clean up resources and is executed after every test method is run.
- The assertEqual() function checks the two given values for equality.