Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Writing Tests with unittest | Testing with unittest and pytest
Python Structural Programming

Writing Tests with unittest

Swipe um das Menü anzuzeigen

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.

Note
Note

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.

1234567891011121314151617181920212223
import 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)
Note
Note

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.

question mark

Which unittest assertion method should you use to check that a function call raises an expected exception?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 5. Kapitel 2

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 5. Kapitel 2
some-alt