0
0
PyTesttesting~15 mins

Test classes in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify calculator operations using pytest test class
Preconditions (2)
Step 1: Create a test class named TestCalculator
Step 2: Inside the class, write a setup method to create a Calculator instance
Step 3: Write a test method test_add to verify addition of 2 and 3 equals 5
Step 4: Write a test method test_subtract to verify subtraction of 5 from 10 equals 5
Step 5: Write a test method test_multiply to verify multiplication of 4 and 3 equals 12
Step 6: Write a test method test_divide to verify division of 10 by 2 equals 5
Step 7: Run pytest and observe the test results
✅ Expected Result: All test methods pass confirming Calculator operations work correctly
Automation Requirements - pytest
Assertions Needed:
assert addition result equals expected
assert subtraction result equals expected
assert multiplication result equals expected
assert division result equals expected
Best Practices:
Use test classes to group related tests
Use setup method for common test setup
Use clear and descriptive test method names
Use assert statements for validation
Automated Solution
PyTest
import pytest

class Calculator:
    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

    def divide(self, a, b):
        if b == 0:
            raise ValueError("Cannot divide by zero")
        return a / b

class TestCalculator:
    def setup_method(self):
        self.calc = Calculator()

    def test_add(self):
        result = self.calc.add(2, 3)
        assert result == 5

    def test_subtract(self):
        result = self.calc.subtract(10, 5)
        assert result == 5

    def test_multiply(self):
        result = self.calc.multiply(4, 3)
        assert result == 12

    def test_divide(self):
        result = self.calc.divide(10, 2)
        assert result == 5

The Calculator class provides basic math operations.

The TestCalculator class groups tests for these operations.

The setup_method runs before each test to create a fresh Calculator instance.

Each test method calls one Calculator method and asserts the result matches the expected value.

This structure keeps tests organized and avoids repeating setup code.

Common Mistakes - 4 Pitfalls
Not using a test class and writing standalone test functions
Not using setup_method and creating Calculator instance inside each test
Using print statements instead of assert for validation
Using unclear test method names like test1, test2
Bonus Challenge

Now add data-driven testing with 3 different input sets for the add method

Show Hint