0
0
PyTesttesting~15 mins

Grouping related tests in PyTest - Build an Automation Script

Choose your learning style9 modes available
Group related tests for arithmetic operations
Preconditions (2)
Step 1: Create a test class named TestArithmetic
Step 2: Inside the class, write three test methods: test_addition, test_subtraction, test_multiplication
Step 3: In test_addition, assert that 2 + 3 equals 5
Step 4: In test_subtraction, assert that 5 - 2 equals 3
Step 5: In test_multiplication, assert that 3 * 4 equals 12
Step 6: Run pytest on the test_arithmetic.py file
✅ Expected Result: All three tests run together as part of the TestArithmetic group and pass successfully
Automation Requirements - pytest
Assertions Needed:
Assert equality of arithmetic results using assert statements
Best Practices:
Group related tests inside a test class
Use clear and descriptive test method names
Keep tests independent and simple
Automated Solution
PyTest
import pytest

class TestArithmetic:
    def test_addition(self):
        assert 2 + 3 == 5

    def test_subtraction(self):
        assert 5 - 2 == 3

    def test_multiplication(self):
        assert 3 * 4 == 12

This code defines a test class TestArithmetic to group related arithmetic tests.

Each test method checks one operation using simple assert statements.

Grouping tests in a class helps organize them logically and run them together.

Running pytest on this file will discover and run all three tests, showing clear pass/fail results.

Common Mistakes - 3 Pitfalls
Writing multiple unrelated tests as standalone functions without grouping
Using unclear test method names like test1, test2
Combining multiple assertions in one test method for different operations
Bonus Challenge

Now add a test for division inside the TestArithmetic class with inputs 10 and 2, asserting the result is 5

Show Hint