DEV Community


Posted on

Python Unit Testing

Coders write much code. How do you know that code does what it's supposed to do?

One way is to do "unit tests". A unit test tests a method and tests if the inputs matches the outputs.

Unit Test with Python

Hockey dockey professori. Want to see that in Python?

Start with a simple program:

def inc_by_one(x):
    return x + 1

Then test that with the unittest module (

import unittest
import program

class MyModuleTest(unittest.TestCase):

    def test_inc_by_one(self):
        assert(program.inc_by_one(2) == 3)

if __name__ == '__main__':

Pay attention to this line:

        assert(program.inc_by_one(2) == 3)

It tests if the input (2) matches the output (3).

If you run the program the test will be run:

Ran 1 test in 0.000s


Holy ravioli, the test passed!

Learn Python:

Top comments (0)