Tuesday , June 10 2025

What is Unit Testing? Best to do

What is unit testing learn
What is unit testing? learn

✅ What Is Unit Testing?

Unit testing is mostly done by developers. It is the process of testing individual pieces (units) of code like units of code, such as functions, methods, or classes, are tested in isolation to ensure they function correctly, The developer writes scripts to do unit test validation.  There are many unit test frameworks available as per programming language used in development.

Why is Unit Testing Important?

  • If unit testing is done earlier for small pieces of code, then it Catches bugs early.
  • It allows code to be made easier to maintain.
  • It encourages better code structure.
  • Gives confidence during changes or refactoring.

🛠️ Tools

Below are a few unit testing tools those depend on the language you use. For example:

Language Common Unit Test Framework
Python unittest or pytest
JavaScript Jest or Mocha
Java JUnit
C# NUnit

To understand how unitn testing is done Let’s start with Python using unittest


🧪 Example in Python (with unittest)

🧾 Step 1: Your Code (Function to Test)

This is a simple Python function add(a, b) that returns the sum of a and b. This is the unit of code we want to test

# calculator.py
def add(a, b):
    return a + b

🧪 Step 2: Write Unit Test

# test_calculator.py
import unittest
from calculator import add

class TestCalculator(unittest.TestCase):

    def test_add_positive_numbers(self):
        self.assertEqual(add(2, 3), 5)

    def test_add_negative_numbers(self):
        self.assertEqual(add(-2, -3), -5)

    def test_add_mixed_numbers(self):
        self.assertEqual(add(-2, 3), 1)

if __name__ == '__main__':
    unittest.main()

▶️ Run the Test

In your terminal or command line:

python test_calculator.py

If everything is good, you’ll see:

...
----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

🔍 Key Concepts in Unit Testing

Concept Description
assertEqual(a, b) Checks if a == b
assertTrue(x) Checks if x is True
assertRaises Checks if a function raises an error
Test Isolation Each test runs independently
Setup/Teardown Use setUp() and tearDown() to prepare/clean up

Learn Manual Testing 

About testautomation.in

Check Also

Waterfall model diagram flowchart

Learn Advantage of waterfall model in software engineering and its 6 phases

As we are moving forward to learning the Manual Testing tutorial course, we will look …

Leave a Reply

Your email address will not be published. Required fields are marked *