Using 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
Method | Check | Example |
---|---|---|
assertEqual(a, b) | a == b | assertEqual(sum([1, 2, 3]), 6) |
assertNotEqual(a, b) | a != b | assertNotEqual(1, 2) |
assertTrue(x) | bool(x) is True | assertTrue(isinstance(123, int)) |
assertFalse(x) | bool(x) is False | assertFalse(isinstance("hello", int)) |
assertIs(a, b) | a is b | a = 1, b = a |
assertIsNone(x) | x is None | book.price = None |
assertIn(a, b) | a in b | assertIn(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
.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Awesome!
Completion rate improved to 3.13
Using Assert Methods in Unittest: Validating Test Results
Deslize para mostrar o 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
Method | Check | Example |
---|---|---|
assertEqual(a, b) | a == b | assertEqual(sum([1, 2, 3]), 6) |
assertNotEqual(a, b) | a != b | assertNotEqual(1, 2) |
assertTrue(x) | bool(x) is True | assertTrue(isinstance(123, int)) |
assertFalse(x) | bool(x) is False | assertFalse(isinstance("hello", int)) |
assertIs(a, b) | a is b | a = 1, b = a |
assertIsNone(x) | x is None | book.price = None |
assertIn(a, b) | a in b | assertIn(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
.
Obrigado pelo seu feedback!