杰瑞科技汇

Python assertequals用法与assert有何不同?

Of course! This is a very common point of confusion for developers new to Python, especially those coming from languages like Java or C#.

Python assertequals用法与assert有何不同?-图1
(图片来源网络,侵删)

Here's a detailed breakdown of assertEquals in Python.

The Short Answer: There is No assertEquals

Python does not have a built-in function called assertEquals. This function is standard in the JUnit testing framework for Java, the NUnit framework for C#, and others, but it is not part of Python's core language or its standard testing library, unittest.

The Python equivalent is assertEqual().


The Correct Way: unittest.TestCase.assertEqual()

In Python's standard unittest framework, you get assertEqual() by creating a test class that inherits from unittest.TestCase.

Python assertequals用法与assert有何不同?-图2
(图片来源网络,侵删)

How to Use assertEqual()

  1. Import unittest.
  2. Create a class that inherits from unittest.TestCase.
  3. Write test methods (methods starting with test_).
  4. Inside your test methods, call self.assertEqual(actual_value, expected_value, msg).

Here is a complete example:

import unittest
# The code you want to test
def add(a, b):
    return a + b
# Your test class
class TestMathFunctions(unittest.TestCase):
    def test_add_positive_numbers(self):
        # Arrange: Set up your test data
        a = 2
        b = 3
        expected_result = 5
        # Act: Call the function you are testing
        actual_result = add(a, b)
        # Assert: Check if the actual result matches the expected result
        # This is the correct Python equivalent of assertEquals
        self.assertEqual(actual_result, expected_result, "Adding 2 and 3 should equal 5")
    def test_add_negative_numbers(self):
        self.assertEqual(add(-1, -5), -6, "Adding -1 and -5 should equal -6")
    def test_add_with_zero(self):
        self.assertEqual(add(10, 0), 10, "Adding 10 and 0 should equal 10")
# This allows the test to be run from the command line
if __name__ == '__main__':
    unittest.main()

Running the Test

Save the code above as a file (e.g., test_my_code.py) and run it from your terminal:

python -m unittest test_my_code.py

Output:

...
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK

The indicates that each test method passed. If a test fails, unittest will give you a detailed error message.

Python assertequals用法与assert有何不同?-图3
(图片来源网络,侵删)

Common assertEqual Mistakes and How to Avoid Them

The Classic assertEqual vs assertTrue Mistake

A very common error for beginners is to use assertEqual for boolean checks, which is redundant and less readable.

Incorrect (but will work):

def test_is_even(self):
    self.assertEqual(is_even(4), True, "4 should be even")

Correct and More Pythonic: Use assertTrue or assertFalse. It's more direct and what other developers expect.

def test_is_even(self):
    self.assertTrue(is_even(4), "4 should be even")
def test_is_odd(self):
    self.assertFalse(is_even(3), "3 should not be even")

Forgetting to Inherit from unittest.TestCase

If you forget to inherit, you won't have access to self.assertEqual and your code will crash with an AttributeError.

Incorrect:

class TestMyCode: # <-- Missing (unittest.TestCase)
    def test_something(self):
        self.assertEqual(1, 1) # <-- AttributeError: 'TestMyCode' object has no attribute 'assertEqual'

Correct:

class TestMyCode(unittest.TestCase): # <-- Correct inheritance
    def test_something(self):
        self.assertEqual(1, 1)

Other Useful unittest Assertions

unittest.TestCase provides a rich set of assertions. Here are the most common ones:

Assertion Checks if... Example
assertEqual(a, b) a == b self.assertEqual("hello", "hello")
assertNotEqual(a, b) a != b self.assertNotEqual("hello", "world")
assertTrue(x) x is True self.assertTrue(is_valid_user(user))
assertFalse(x) x is False self.assertFalse(is_locked(file))
assertIsNone(x) x is None self.assertIsNone(get_user(999))
assertIsNotNone(x) x is not None self.assertIsNotNone(get_user(1))
assertIn(a, b) a is in b (for sequences/dicts) self.assertIn("apple", fruits)
assertNotIn(a, b) a is not in b self.assertNotIn("banana", fruits)
assertRaises(Exception, func, *args) Calling func raises Exception self.assertRaises(ValueError, int, "not_a_number")

Alternative Testing Frameworks

While unittest is built-in, many developers prefer more modern and expressive frameworks.

Pytest

Pytest is extremely popular because it's simple, powerful, and doesn't require you to write classes or inherit from anything.

Pytest Equivalent:

You just use standard Python assert statements.

# test_with_pytest.py
def add(a, b):
    return a + b
def test_add_positive_numbers():
    result = add(2, 3)
    assert result == 5  # This is all you need!
def test_add_with_zero():
    result = add(10, 0)
    assert result == 10

Running Pytest:

  1. Install pytest: pip install pytest
  2. Run it: pytest test_with_pytest.py

Pytest automatically discovers files starting with test_ or ending with _test.py. It's famous for its excellent error messages, which show you exactly what the values were when an assertion failed.

unittest.mock

For testing interactions with external systems (like databases or APIs), the unittest.mock module (or pytest-mock for pytest) is the standard way to create "mock" objects that simulate real behavior without side effects.

Summary

Concept Java / C# Python (unittest) Python (pytest)
Equality Check assertEquals(a, b) self.assertEqual(a, b) assert a == b
Framework JUnit / NUnit Built-in unittest External pytest library
Test Structure Class inheriting from TestCase Class inheriting from TestCase Plain functions

Key Takeaway: If you're using Python's unittest framework, the function is assertEqual(), not assertEquals. For most new projects, however, pytest is often a more pleasant and productive choice.

分享:
扫描分享到社交APP
上一篇
下一篇