Problem Formulation
Say, you’ve written a number of unit tests using the unittest module in Pyhton. How can you disable specific unit tests temporarily? In other words:
How to skip a unit test in Python’s unittest module?
β₯οΈ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month
Example: Given the following three unit tests.
def test_1():
print('Test case 1')
def test_2():
print('Test case 2')
def test_3():
print('Test case 3')How to disable tests 1 and 2?
Method 1: Skip Test with unittest.skip Decorator
You can disable individual tests by placing the @unittest.skip decorator in front of the function, class, or method definition.
- Use
@unittest.skip('Your reason for skipping')to give a reason for skipping it. - Use
@unittest.skipif you don’t want to give a reason.
Here’s how you’d skip unit tests 1 and 2 in the provided example.
@unittest.skip('Reason for skipping')
def test_1():
print('Test case 1')
@unittest.skip
def test_2():
print('Test case 2')
def test_3():
print('Test case 3')Method 2: Rename Tests to Skip
A simple and dirty, but effective method to skip tests is to prefix them with a single underscore. For example, rename your unit test function test_1 to _test_1 and it will be disabled.
def _test_1():
print('Test case 1')
def _test_2():
print('Test case 2')
def test_3():
print('Test case 3')Method 3: Block Comment
Another alternative is to block comment the unit tests you want to disable using either the hashtag symbol # or the triple quotes '''def test ... ''' to comment out the test case.
#def test_1():
# print('Test case 1')
'''
def test_2():
print('Test case 2')
'''
def test_3():
print('Test case 3')Summary
There are three ways to skip unit tests in Python:
- Using the decorator
@unittest.skipin front of the function to be skipped. - Adding a single underscore as a prefix such as in
_test_1instead oftest_1. - Commenting out the method to be skipped.
You can see all three ways to skip the execution of the unit test in the following summarized example:
import unittest
class TestStringMethods(unittest.TestCase):
def _test_1(self):
print('test 1')
# def test_2(self):
# print('test 2')
@unittest.skip
def test_3(self):
print('test 3')
if __name__ == '__main__':
unittest.main()
Now, none of the three functions are executed if you run this script.