Repaso
Español
TestingCoreTST-05

How do you assert that code raises a ValueError in pytest?

Options

  1. assert raises(ValueError) placed after the call
  2. with pytest.raises(ValueError): parse('x') (Correct option)
  3. try/except followed by assert True
  4. @pytest.mark.error above the test

Answer

with pytest.raises(ValueError): parse("x")

Why

The test passes only if the code inside the with block raises ValueError; if no error happens, the test fails.

You can also check the message: pytest.raises(ValueError, match="invalid").

A hand-written try/except that does nothing when no error occurs would pass silently and hide bugs.

Remember

Expect an error → with pytest.raises(...).

Key terms

Practice this question in Repaso