Assertequals vs assertequal in python

When writing unit tests in Python, it is common to use the assertEqual method from the unittest module to check if two values are equal. However, there is also a similar method called assertEquals that is sometimes used instead. In this article, we will explore the differences between these two methods and discuss which one is better to use in different scenarios.

Option 1: Using assertEqual

The assertEqual method is a built-in assertion method provided by the unittest module. It takes two arguments and checks if they are equal. If they are not equal, it raises an AssertionError with a default error message.

import unittest

class MyTestCase(unittest.TestCase):
    def test_something(self):
        value1 = 10
        value2 = 20
        self.assertEqual(value1, value2, "Values are not equal")

In the above example, the assertEqual method is used to check if value1 and value2 are equal. If they are not equal, the test will fail and the error message “Values are not equal” will be displayed.

Option 2: Using assertEquals

The assertEquals method is not a built-in method in Python, but it is sometimes used as an alternative to assertEqual. It works in a similar way, taking two arguments and checking if they are equal. However, it does not provide a way to customize the error message.

import unittest

class MyTestCase(unittest.TestCase):
    def test_something(self):
        value1 = 10
        value2 = 20
        self.assertEquals(value1, value2)

In the above example, the assertEquals method is used to check if value1 and value2 are equal. If they are not equal, the test will fail and a default error message will be displayed.

Option 3: Which one is better?

Both assertEqual and assertEquals methods serve the same purpose of checking if two values are equal. However, it is generally recommended to use assertEqual over assertEquals for the following reasons:

  • Consistency: assertEqual is a built-in method provided by the unittest module, making it more consistent with other assertion methods in the module.
  • Customizable error messages: assertEqual allows you to provide a custom error message, which can be helpful in identifying the cause of the failure.
  • Compatibility: assertEqual is supported in all versions of Python, while assertEquals may not be available in some versions or future releases.

In conclusion, it is recommended to use the assertEqual method for checking equality in unit tests in Python. It provides consistency, customizable error messages, and better compatibility across different Python versions.

import unittest

class MyTestCase(unittest.TestCase):
    def test_something(self):
        value1 = 10
        value2 = 20
        self.assertEqual(value1, value2, "Values are not equal")
Rate this post

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents