Unit Test in Python
Python Unit Test is something you will encounter in your intermediate term of python journey, Its good practice to follow unit test as it allows you to test a single unit of logic. I am not going into too much depth of advantage and disadvantages of unit test and why you should use it, you can find many more posts on the topic. My focus here to show you some real code quickly which helps you to build a quick understanding of the topic.
Following is the simple program we will be using to see unit test in reality. Just go through it and I will provide a quick explanation of steps. Detailed step by step explanation exist at the end of this post.
Unit test Part:
First import unit test libraries
Then import your program:
Now you need to create a class say and override with `unittest.Testcase`
Under this class create few methods. First of all you will define some setUp methods as below:
In above code snippet you basically instantiated you class as self.calc, this is all covered under setup menthod, basically you are setting up your environment.
Next, we will create further few method, that will basically perform our real test of the unit of our interest.
Complete code looks like:
A line-by-line examination shows that this example:
- First imports the functionality you need from Python’s unittest module. You are also importing your own class, Calculate, so that you can test its methods. You do this in the setUp method, which is executed before each test, so that you need to define your instance only once and have it created before each test.
- Then you can write your test and again the standard is to append your test name with append_testand explain what the test is doing briefly in the rest of the name. Here you are checking if the add method returns the correct result. To do this, you make use of the assertEqual method provided by the imported unittest module. This checks if the first argument is equal to the second. In this example, you are checking whether 5 is equal to the result of calling your add method on 2 and 3. In this case, the test passes as your code works and displays the following result in the terminal.