Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Using Assertions | Writing Effective Unit Tests
Python Unit Testing Fundamentals

bookUsing Assertions

Stryg for at vise menuen

Assertions are the foundation of effective unit tests in Python. They allow you to specify the conditions that must be met for your code to be considered correct. When you write a unit test using the unittest framework, you use assertion methods to compare actual results to your expectations. If an assertion fails, the test fails, signaling that your code may not be working as intended.

even.py

even.py

test_even.py

test_even.py

copy

In the code sample above, you see two commonly used assertion methods: assertEqual and assertTrue. Use assertEqual when you want to check if two values are exactly the same, such as verifying that the output of a function matches an expected result. Use assertTrue when you need to confirm that an expression evaluates to True, which is helpful for checking conditions or boolean returns.

odd.py

odd.py

test_odd.py

test_odd.py

copy
Note
Note

Choosing the right assertion method makes your tests clearer and more reliable. For example, use assertFalse to check that a condition is not true, and assertIn to confirm that an item exists within a collection. Matching your assertion to the specific outcome you expect helps make failures easier to diagnose.

question mark

Which assertion checks if two values are equal in unittest?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 1

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 2. Kapitel 1
some-alt