Python Testing: Creating unit test in python
Tags: python, testing, tutorial, oop
Published: 2020-10-22 15:23:18


As developers or programmers, call yourself anyone. As long as you write code there is often one thing that gets overlooked. Testing. Testing is that part of development where you’re suppose to rigorously test your applications to ensure that they meet the required functionalities.

Let’s start of with why we even do testing in the first place:

1. **The need for less manual testing**.Because the test cases are pre-written, there is no real reason to conduct manual testing anymore. Most times, especially with large applications you have to run through a lot of stages in the software to test if a certain feature works. This could be avoided with testing. Imagine having to use certain inputs every time your application runs. With testing this would be inputted automatically over each run.

2. **Allows for better structure of your code**. It is of a best practice to create your test cases before development. This forces you to think of the system as a whole before you start developing.

3. **Allows for faster testing in long run**. When coding, the implementation of a function can change however, the output remains the same. Instead of manually testing this every time a function’s implementation changes, you can simply implement specific test cases that can run multiple test cases at a time.

![Monitor](https://dev-to-uploads.s3.amazonaws.com/i/1307e3a3ldrwip0mmswd.png)

##Getting Started

We will be focusing on a specific type of testing and that is unit testing. This specific type of test is for testing small units of code such as a function or a class.

To create our unit test we will be using the python standard library `unittest`. This way of creating test cases uses OOP(Object Oriented Programming) by creating a class that will house all our test cases. This will allow us to run all the test cases in the class at once.

**Note: You can use any IDE or text editor that your familiar with (default python IDE can be used). For this, I will be demonstrating using Visual Studio Code with a python extension.**

We will first import our unit test library:

```python
import unittest
```

Now to make our class declaration:

```python
class TestingClass(unittest.TestCase):
```

Note that `(unittest.TestCase)` is inheritance in python. Essentially giving functionality to the class.

Inside the class add our first function:

```python
def test_first(self):
    test_var = 9 + 1
    self.assertEqual(11,test_var)
```

`self.assertEqual` is a method given by the previously inherited class (unittest.TestCase). This method tests if the 2 variables are equally of the same value.

Adding our test runner. This is what makes our unit test run:

```python
unittest.main()
```
This is what the completed code should look like:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2jr157xlef58mii3dmnr.png)

The above code demonstrates testing if 9 + 1 is equal to 11. If you know any basic math you should know that 9+1 = 10. Hence this test case would fail.

Output:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lc2xkxh5c3xhz775rs9i.png)

As you should have already guessed. Failure!

The fix is simple. Modify the code to:

```python
test_var = 9 + 2
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5tsup1hkrb1qwt46eris.png)

Output:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lbonj194z6pdv5d7n5c6.png)

##Testing Outside Functions

For testing outside of functions, the previous example might not be realistic. Let’s replace the `test_var` values to now come from a function. We will add a functional declaration to the top of our file.

```python
def add(a,b):
    return a + b
```
This function adds 2 numbers together. Replace 9 + 2 with the function call `add(9,2)` and then run your code.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/phjv9ub05331ag3wzftc.gif)

We have only implemented one test case so far. Each function/method (both are the same thing in this case) in the `TestingClass` represents a single test case.

Lets add another test case called `test_multiple_num_addition`.

```python
def test_multiple_num_addition(self):
    test_var = add(10,20,30,40) 
    self.assertEqual(100,test_var)
```

**Note: All the names of the test cases created should be preceded with the word “test” or else it will not be recognized by the test runner.**

Your code should look like the following below:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7b8ah2tq7sbt3bcng3r6.png)

After running:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bopbohe0hjx4mun8e9y2.gif)

This will obviously fail because the function parameters only accept 2 arguments. But what if we really wanted to add more numbers?

This can be solved by doing a change to the add function:

```python
def add(*values):
    return sum(values)
```
Notice the asterisk (*) left of the values argument. This allows you to input multiple arguments as well as allowing the values to be stored as a tuple.

Your code before execution:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/opiv8jv2glcghezuy44q.png)

Your code while being executed:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ydq5xonyluh7hz6kamx9.gif)

And Success!

Putting an asterisk before your variable in the function parameters is called non keyword arguments. Want more information checkout the article below.

##Summary

Giving testing a try might give your code additional robustness. It also has the benefit of changing the way you approach development. Having a testing mindset can ensure that there are less errors in production and less repetitive manual testing during development.

If you liked this article and want to support. Buy me a coffee. The link is provided below.

<a href="https://www.buymeacoffee.com/PlatinumCoder" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>