DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

How to simplify your unit test?

If I say that I know something magic which will simplify your unit tests, do you believe me?

You should, because we will see it today. And this magic is call parametrized tests


What are parametrized tests?

Parametrized tests are unit tests to which we will inject variables as parameters, which will make it possible to replay the same test with another context.


How does it work?

Suppose that we want to test the following function :

def is_positif_strict(num_to_test: int) -> bool:
    return num_to_test > 0
Enter fullscreen mode Exit fullscreen mode

Before parametrized tests, to test it we should either:

  • create a lot of functions for each sub test
  • create one big function which will execute all the tests

We are not lying or hiding something here, the first solution is painful and is less maintainable, the second one is painful is a subtest fail and you have to understand which one and why.

But now with Pytest, you can just declare your tests like this

import pytest

testdata = [
    (-1, False),
    (0, False),
    (1, True),
]

@pytest.mark.parametrize("num_to_test, expected", testdata)
def test_is_positif_strict(num_to_test, expected):
    assert is_positif_strict() == expected
Enter fullscreen mode Exit fullscreen mode

In this example, we saw that we add the annotation @pytest.mark.parametrize with two parameters:

  • a string containing the list of variable names we want to inject (variable names separated by a comma)
  • an array containing all the values we want to inject (If you have multiple parameters, it will be an array of tuples)

Now, with this new knowledge, if you have to write unit tests, you will see that it will be far easier and more simple to read and maintain.

For the one who already used an array and did a loop on it in a single unit test, here is what you gain : visibility.

Contrary to the loop in your unit test, each entry in the array will generate a dedicated unit test. So if you have 40 use cases to test, it will generate 40 unit tests in your report. And it's really helpful if some of those a failing.

For the one who are not already convinced, think about testing regexes. For this kind of methods, you ALWAYS have a lot of use cases. As a result, a tool like that will make your developer's life more enjoyable!


If you are not using Python, you must know that you can do the same thing in Java or in Go.
So, if you are interested by this, let me know in the comments!

I hope it will help you! 🍺


You want to support me?

Buy Me A Coffee

Top comments (2)

Collapse
 
edenwheeler profile image
Eden Wheeler

This is really helpful article.

Collapse
 
mxglt profile image
Maxime Guilbert

I'm glad it helps you :)