0
0
PyTesttesting~15 mins

@pytest.mark.xfail for expected failures - Build an Automation Script

Choose your learning style9 modes available
Automate a test that is expected to fail using @pytest.mark.xfail
Preconditions (2)
Step 1: Create a test function that asserts 1 + 1 equals 3
Step 2: Mark the test function with @pytest.mark.xfail to indicate it is expected to fail
Step 3: Run the test suite using pytest
Step 4: Observe that the test is reported as an expected failure, not a failure
✅ Expected Result: The test is reported as xfailed (expected failure) by pytest, not as a failure or error
Automation Requirements - pytest
Assertions Needed:
Assert that 1 + 1 == 3 inside the test function
Best Practices:
Use @pytest.mark.xfail decorator to mark expected failures
Keep test functions simple and focused
Run tests with clear output to verify xfail behavior
Automated Solution
PyTest
import pytest

@pytest.mark.xfail
 def test_addition_expected_failure():
     assert 1 + 1 == 3

if __name__ == "__main__":
    import sys
    import pytest
    sys.exit(pytest.main([__file__]))

The @pytest.mark.xfail decorator marks the test as an expected failure. This means pytest will run the test but will not count it as a failure if it fails. Instead, it will report it as 'xfailed'.

The test function test_addition_expected_failure asserts that 1 + 1 equals 3, which is false, so it will fail normally. But because of the @pytest.mark.xfail, pytest expects this failure.

The if __name__ == "__main__" block allows running the test file directly, which helps beginners run and see the test output easily.

Common Mistakes - 3 Pitfalls
Not using @pytest.mark.xfail and expecting the test to pass
Using @pytest.mark.xfail but the test actually passes
Marking too many tests as xfail without fixing them later
Bonus Challenge

Now add three test functions with different expected failures using @pytest.mark.xfail, each failing for a different reason.

Show Hint