Writing Tests with unittest
Veeg om het menu te tonen
When you want to ensure your code works as expected, writing automated tests is essential. Python's unittest module is a built-in framework that lets you create and organize tests easily. You write test cases by creating classes that inherit from unittest.TestCase. Inside these classes, you define methods whose names start with test_. Each method checks a specific aspect of your code.
A test suite is a collection of test cases that can be run together. By default, unittest discovers and runs all test_ methods in your TestCase classes. To check if your code produces the expected results, you use assertion methods such as assertEqual, assertTrue, assertFalse, and assertRaises. These assertion methods compare actual outcomes to expected ones, and report failures if they do not match.
To run your tests, you can use the command line or call unittest.main() at the bottom of your test file.
assertRaises follows a distinct pattern compared to other assertion methods like assertEqual or assertTrue. Instead of checking a final value, it operates as a context manager using the with statement to create a guarded zone. This allows the test to monitor code as it executes and "catch" the expected error.
1234567891011121314151617181920212223import unittest def add(a, b): return a + b def divide(a, b): return a / b class TestMathFunctions(unittest.TestCase): def test_add_positive_numbers(self): self.assertEqual(add(2, 3), 5) def test_add_negative_numbers(self): self.assertEqual(add(-2, -3), -5) def test_divide_normal(self): self.assertAlmostEqual(divide(10, 2), 5.0) def test_divide_by_zero(self): with self.assertRaises(ZeroDivisionError): divide(10, 0) unittest.main(argv=['first-arg-is-ignored'], exit=False)
Function unittest.main() in this chapter includes a couple of extra parameters required only for this learning environment. They help the code run correctly on the platform and are not part of the core Python concepts you need to learn right now.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.