What is unittest?
A built-in Python testing framework based on the xUnit architecture used for writing and running automated tests.
How do you import unittest?
import unittest
What is a Test Case?
The smallest unit of testing in unittest; a class that inherits from unittest.TestCase.
What is a Test Suite?
A collection of test cases or test suites that are executed together.
What is a Test Runner?
The component that orchestrates test execution and reports results.
What is unittest.TestCase used for?
To define individual test methods and provide assertion methods for checking conditions.
How do you define a test method?
Define a method inside a TestCase subclass whose name starts with test_.
How do you run tests directly from a file?
Add: if __name__ == ‘__main__’: unittest.main()
What does unittest.main() do?
Automatically discovers and runs all test methods in the current module.
How do you set up code before each test?
Define a setUp(self) method in your test class.
How do you clean up code after each test?
Define a tearDown(self) method in your test class.
How do you run setup code once per class?
Use @classmethod def setUpClass(cls):
How do you run teardown code once per class?
Use @classmethod def tearDownClass(cls):
What is an Assertion Method?
Methods used to check for expected results (e.g., assertEqual, assertTrue, etc.).
Example of assertEqual
self.assertEqual(x, y) passes if x == y.
Example of assertTrue
self.assertTrue(condition) passes if condition is True.
Example of assertFalse
self.assertFalse(condition) passes if condition is False.
Example of assertRaises
Used to verify an exception is raised: with self.assertRaises(ValueError): func()
Example of assertIn
self.assertIn(item, container) checks if item is in container.
How do you skip a test?
Use @unittest.skip(‘reason’) above the test method.
How do you conditionally skip a test?
Use @unittest.skipIf(condition, ‘reason’).
How do you expect a failure?
Use @unittest.expectedFailure to mark tests expected to fail.
How do you create a Test Suite manually?
suite = unittest.TestSuite() then suite.addTest(…).