DEV Community

Testrig Technologies
Testrig Technologies

Posted on

Writing Your First Automated Test Using Python (unittest Framework)

Continuing our Python Testing Series. If you missed the previous article on Pytest, read it here:
🔗 How to Get Started With Pytest – The Best Python Testing Framework

Why Start with unittest?

While frameworks like Pytest offer a sleek and powerful testing experience, unittest—Python's built-in test framework—is a valuable place to start your testing journey.

Here’s why:

✅ No installation needed – it comes bundled with Python.

✅ Industry standard – used in many production and enterprise-grade projects.

✅ Great for learning fundamentals – teaches you how tests are structured, run, and validated.

✅ Easy to integrate – works out-of-the-box with CI/CD pipelines and tools like Jenkins or GitHub Actions.

For beginners, learning unittest helps build the right foundation for scalable and reliable test automation.

What Is unittest?

unittest is a unit testing framework built into the Python standard library. It’s based on the xUnit style, popularized in other languages like Java (JUnit) and C# (NUnit).

In unittest, you:

  • Write test cases as classes.
  • Use special methods like setUp() and tearDown() to manage test context.
  • Validate results using built-in assertions.

This structure keeps your code organized, readable, and repeatable—three things that matter in real-world test automation.

Let’s Build Your First Python Test (Step-by-Step)

Imagine you're developing a simple utility that performs addition. You want to verify that it behaves correctly.

Step 1: Create the Function to Be Tested

calculator.py

def add(a, b):
return a + b

This is your production code. In real scenarios, this could be a utility in your backend application.

Step 2: Write the Test Case
Now create a test file: test_calculator.py

import unittest
from calculator import add

class TestCalculator(unittest.TestCase):

def test_add_positive_numbers(self):
    result = add(5, 3)
    self.assertEqual(result, 8)

def test_add_negative_numbers(self):
    result = add(-2, -5)
    self.assertEqual(result, -7)

def test_add_zero(self):
    result = add(0, 0)
    self.assertEqual(result, 0)
Enter fullscreen mode Exit fullscreen mode

if name == 'main':
unittest.main()

What’s Going On Here?

Image description

Example: Testing for Exceptions

def divide(a, b):
return a / b

class TestDivision(unittest.TestCase):

def test_divide_by_zero(self):
    with self.assertRaises(ZeroDivisionError):
        divide(10, 0)
Enter fullscreen mode Exit fullscreen mode

This is crucial in real projects where you want to make sure your code handles edge cases safely.

Organizing Your Test Project (Real-World Structure)

As your project grows, structuring tests correctly helps maintain scalability.

📁 Example structure:

my_project/
├── src/
│ └── calculator.py
├── tests/
│ └── test_calculator.py
├── requirements.txt
└── README.md

To run all your tests, simply use:

python -m unittest discover -s tests

This command will:

Search all files starting with test_

Run all test methods inside

Using setUp() and tearDown() (Managing Test Context)

Sometimes you need to set up data before every test (and clean up after). That’s where setUp() and tearDown() help.

class TestDataOperations(unittest.TestCase):

def setUp(self):
    self.numbers = [1, 2, 3]

def tearDown(self):
    self.numbers = []

def test_list_append(self):
    self.numbers.append(4)
    self.assertEqual(self.numbers, [1, 2, 3, 4])
Enter fullscreen mode Exit fullscreen mode
  • setUp() runs before every test method
  • tearDown() runs after every test method

This ensures your tests are independent and clean — no leftover data from other tests.

Running Tests with Verbosity
To see a more detailed output, use the -v flag:
python -m unittest -v tests/test_calculator.py

You’ll see:

test_add_positive_numbers (TestCalculator) ... ok
test_add_zero (TestCalculator) ... ok

Useful when running dozens (or hundreds) of test cases.

When to Use unittest vs Pytest?

Image description

Final Thoughts

Learning unittest isn’t just about syntax. It’s about thinking like a tester:

  • What should this function really do?
  • How can I prove that?
  • What could go wrong?

If you’re a Python developer, or even someone shifting toward test automation, mastering unittest gives you the confidence to write clean, testable, and production-ready code.

Need Expert Help with Python Automation?
At Testrig Technologies, we build scalable, maintainable test automation frameworks using Python, Pytest, Selenium, and more. From startups to enterprise clients, we help QA teams shift left and reduce manual efforts. Get in touch with a leading QA Automation Testing Company!

Top comments (0)