Skip to content
Python

Unit Testing

Write unit tests using unittest.

By EZ4Code Team
testunittest

Code

import unittest

def add(a, b):
    return a + b

class TestAdd(unittest.TestCase):
    def test_add_int(self):
        self.assertEqual(add(1, 2), 3)

    def test_add_str(self):
        self.assertEqual(add("a", "b"), "ab")

    def test_add_negative(self):
        self.assertEqual(add(-1, -2), -3)

    def setUp(self):
        print("Executed before each test")

    @classmethod
    def setUpClass(cls):
        print("Executed once before all tests")

if __name__ == "__main__":
    unittest.main()

Explanation

unittest provides assertion methods and setUp/tearDown hooks.

More Python Snippets