Python Testing - Given When Then syntax


TDD tip:

You can add GIVEN, WHEN, THEN as a docstring to your tests to better express your intent.

An example👇

def test_all(self):
    """
    GIVEN a PhoneBook with a records property
    WHEN the all method is called
    THEN all numbers should be returned in ascending order
    """

    phone_book = PhoneBook(
        records=[
            ("John Doe", "03 234 567 890"),
            ("Marry Doe", "01 234 567 890"),
            ("Donald Doe", "02 234 567 890"),
        ]
    )

    previous = ""

    for record in phone_book.all():
        assert record[0] > previous
        previous = record[0]