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
.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Awesome!
Completion rate improved to 3.13
Using Assert Methods in Unittest: Validating Test Results
Sveip for å vise menyen
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
.
Takk for tilbakemeldingene dine!