Python assertEqual

Summary: in this tutorial, you’ll learn how to use the Python assertEqual() method to test if two values are equal.

Introduction to the Python assertEqual() method

The assertEqual() is a method of the TestCase class of the unittest module. The assertEqual() tests if two values are equal:

assertEqual(first, second, msg=None)Code language: Python (python)

If the first value does not equal the second value, the test will fail.

The msg is optional. If the msg is provided, it’ll be shown on the test result if the test fails.

Python assertEqual() method example

First, create a new module called main.py and define the add() function:

def add(a, b):
    return a + bCode language: Python (python)

Second, create a test module test_main.py to test the add() function:

import unittest

from main import add


class TestMain(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(1, 2), 3)Code language: Python (python)

Third, run the test:

python -m unittest test_main.py -vCode language: Python (python)

Output:

test_add (test_main.TestMain) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OKCode language: Python (python)

Python assertNotEqual() method

The assertNotEqual() method tests if two values are not equal:

assertNotEqual(first, second, msg=None)Code language: Python (python)

If the first is equal to the second, the test will fail. Otherwise, it’ll pass. For example:

import unittest

from main import add


class TestMain(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(1, 2), 3)

    def test_add_floats(self):
        self.assertNotEqual(add(0.2, 0.1), 0.3)Code language: Python (python)

Run the test:

python -m unittest test_main.py -vCode language: Python (python)

Output:

test_add (test_main.TestMain) ... ok
test_add_floats (test_main.TestMain) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.001s

OKCode language: Python (python)

Since 0.2 + 0.1 returns 0.30000000000000004, it’s not equal to 0.3. Therefore, the following test passes:

self.assertNotEqual(add(0.2, 0.1), 0.3)Code language: Python (python)

Summary

  • Use the assertEqual() method to test if two values are equal.
  • Use the assertNotEqual() method to test if two values are not equal.
Did you find this tutorial helpful ?