Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Using Assert Methods in Unittest: Validating Test Results | Mastering Unittest Framework
Python Advanced Concepts

bookUsing Assert Methods in Unittest: Validating Test Results

The assert methods are part of the unittest.TestCase class and are used to check conditions in your tests. Simply put, each test method in the Test class concludes with a statement such as self.assert.

Commonly Used assert Methods

MethodCheckExample
assertEqual(a, b)a == bassertEqual(sum([1, 2, 3]), 6)
assertNotEqual(a, b)a != bassertNotEqual(1, 2)
assertTrue(x)bool(x) is TrueassertTrue(isinstance(123, int))
assertFalse(x)bool(x) is FalseassertFalse(isinstance("hello", int))
assertIs(a, b)a is ba = 1, b = a
assertIsNone(x)x is Nonebook.price = None
assertIn(a, b)a in bassertIn(2, [1, 2, 3])
assertIsInstance(a, b)isinstance(a, b)assertIsInstance(123, int)

Also, assertRaises(Error, func, *args, **kwargs) is used to test that an error is raised. For example:

with self.assertRaises(ValueError):
    int("xyz")

This checks that converting "xyz" to integer raises ValueError.

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 5. ChapterΒ 2

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Awesome!

Completion rate improved to 3.13

bookUsing Assert Methods in Unittest: Validating Test Results

Swipe to show menu

The assert methods are part of the unittest.TestCase class and are used to check conditions in your tests. Simply put, each test method in the Test class concludes with a statement such as self.assert.

Commonly Used assert Methods

MethodCheckExample
assertEqual(a, b)a == bassertEqual(sum([1, 2, 3]), 6)
assertNotEqual(a, b)a != bassertNotEqual(1, 2)
assertTrue(x)bool(x) is TrueassertTrue(isinstance(123, int))
assertFalse(x)bool(x) is FalseassertFalse(isinstance("hello", int))
assertIs(a, b)a is ba = 1, b = a
assertIsNone(x)x is Nonebook.price = None
assertIn(a, b)a in bassertIn(2, [1, 2, 3])
assertIsInstance(a, b)isinstance(a, b)assertIsInstance(123, int)

Also, assertRaises(Error, func, *args, **kwargs) is used to test that an error is raised. For example:

with self.assertRaises(ValueError):
    int("xyz")

This checks that converting "xyz" to integer raises ValueError.

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 5. ChapterΒ 2
some-alt