Companies
AI AcademyCoursesEventsQuizzesJobsCommunity
How to Write Unit Tests? A Guide with Examples.

How to Write Unit Tests? A Guide with Examples.

What is a unit test, and how do you write one? Learn the steps for writing unit tests—using Python and `pytest` as examples—as well as how to create test scenarios and the differences between unit tests and integration tests.
Techcareer.net
Techcareer.net
●
10.27.2026
●
6 Minutes

Unit testing helps verify whether small, independent parts of a software application work as expected. But how do you write a unit test, and when should you use one? In this guide, you will learn the fundamentals of unit testing, the steps involved in writing tests, and examples from different programming languages.

What Is a Unit Test?

A unit test is a type of software test that verifies the behavior of a small part of an application, such as a single function, method, or class. Its purpose is to check whether the component produces the expected output for specific inputs.

For example, you can test whether a function that adds two numbers returns the correct result. If the function is expected to return 8 when given 3 and 5, a unit test can automatically verify this behavior.

Unit tests help detect bugs early and determine whether code changes have broken existing functionality. This can make maintaining software and adding new features easier.

What Are Unit Tests Used For?

Unit tests are used to verify code correctness during software development. They are particularly useful in frequently updated projects, as they make it easier to determine whether a previously working feature has broken due to a new change.

The main benefits of unit testing include:

  • Detecting bugs early: Unexpected behavior in a function can be identified when a test runs.
  • Making code changes with confidence: Tests can verify whether existing behavior is preserved when new features are added.
  • Supporting code quality: Writing testable code encourages clearer definitions of responsibilities.
  • Contributing to documentation: Tests demonstrate how a function should behave under specific conditions.
  • Automating repetitive checks: They reduce the need to manually verify the same scenarios after every change.

Unit tests cannot identify every software bug on their own. Other testing methods, such as integration testing, may also be necessary to verify interactions between databases, services, and different components.

How to Write a Unit Test

When writing a unit test, you should first identify the purpose of the function you want to test and define its expected behavior. You can then create tests that automatically verify the expected results for different inputs.

You can follow these steps to write a unit test:

  • Identify the unit to test: Focus on the behavior of a single function or method.
  • Create test scenarios: Consider normal inputs as well as empty, invalid, or boundary values.
  • Write the test code: Execute the function and compare the result with the expected value.
  • Run the tests: Check whether the tests pass.
  • Fix bugs and test again: Rerun the tests after making changes to the code.

It is important to keep test code clear and independent. If the result of one test depends on another test running first, identifying bugs can become more difficult.

How to Write a Unit Test in Python: An Example

Python is one of the programming languages you can use to get started with unit testing. In addition to Python's built-in unittest module, you can also use the pytest library, which offers a more concise syntax. In the following example, we will use pytest to test a simple addition function.

First, create the function you want to test in a file named calculator.py:

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

Next, create a file named test_calculator.py in the same project directory and write the test code:

from calculator import topla

def test_topla():
    assert topla(3, 5) == 8

The assert statement checks whether the function's result matches the expected value. If the result is 8, the test passes. If the function returns a different result, the test is reported as a failure.

If pytest is not installed yet, you can install it from the terminal using the following command:

pip install pytest

To run the tests, use this command in the project directory:

pytest

If the test passes, pytest reports that the relevant test was successful. This allows you to automatically verify the function's behavior for the scenario you defined.

Which Scenarios Should You Test When Writing Unit Tests?

Testing only standard inputs may not be enough to verify all the possible behaviors of a function. You should also consider different situations that may occur during actual use.

For example, you can consider the following scenarios for a discount calculation function:

  • Normal case: Applying a 10% discount to a product priced at TRY 1,000.
  • Boundary value: Setting the discount rate to 0%.
  • Upper boundary: Determining the expected behavior when the discount rate is 100%.
  • Invalid input: Ensuring that an appropriate error occurs when a negative discount rate is provided.
  • Special case: Setting the product price to zero.

These scenarios help you verify not only whether the function produces the correct result but also how it handles unexpected inputs. Expected behavior should be defined according to the application's requirements.

What Should You Consider When Writing Unit Tests?

A good unit test is more than just a test that runs successfully. It should also be clear, reliable, and easy to update when necessary.

To achieve this, consider the following points:

  • Focus on a single behavior: It should be clear what the test is verifying.
  • Use meaningful names: The test name should describe the condition being checked as clearly as possible.
  • Keep tests independent: The outcome of one test should not depend on the execution order of other tests.
  • Define expected results correctly: Make sure the test can actually detect incorrect code.
  • Limit external dependencies: Whenever possible, unit tests should run independently of components such as databases or external services.

Additionally, rather than writing a test for every line of code, prioritize critical business rules and behaviors that are more likely to cause errors. The quality of tests is just as important as test coverage.

What Is the Difference Between Unit Testing and Integration Testing?

Unit testing and integration testing are different types of software testing used to verify correctness. The main difference lies in the scope of what is being tested.

A unit test checks the behavior of a single component in isolation, while an integration test examines whether multiple components work together correctly. For example, testing a price calculation function falls under unit testing. Verifying that the same function works with product information retrieved from a database may require integration testing.

These two testing methods are not alternatives to one another. They complement each other by verifying software at different levels.

Learning to write unit tests helps you better understand code behavior and manage changes more safely. You can start with small functions, test different scenarios, and make testing a regular part of your development workflow.


More Stories

Yazılım Dokümantasyonu Nasıl Yazılır? İyi Bir README Rehberi

Yazılım Dokümantasyonu Nasıl Yazılır? İyi Bir README Rehberi

Yazılım dokümantasyonu nasıl yazılır? İyi bir README dosyasının nasıl hazırlanacağını, hangi bölümleri içermesi gerektiğini ve Markdown ile dokümantasyon oluşturma adımlarını keşfet.
27.10.2026
●
6 Minutes
TECHCAREER
About Us
techcareer.net
Artificial Intelligence (AI) Competency Academy
SOCIAL MEDIA
LinkedinTwitterInstagramYoutubeFacebook

tr

en

All rights reserved
© Copyright 2026
support@techcareer.net
İşkur logo

Kariyer.net Elektronik Yayıncılık ve İletişim Hizmetleri A.Ş. Özel İstihdam Bürosu olarak 31/08/2024 – 30/08/2027 tarihleri arasında faaliyette bulunmak üzere, Türkiye İş Kurumu tarafından 26/07/2024 tarih ve 16398069 sayılı karar uyarınca 170 nolu belge ile faaliyet göstermektedir. 4904 sayılı kanun uyarınca iş arayanlardan ücret alınmayacak ve menfaat temin edilmeyecektir. Şikayetleriniz için aşağıdaki telefon numaralarına başvurabilirsiniz. Türkiye İş Kurumu İstanbul İl Müdürlüğü: 0212 249 29 87 Türkiye iş Kurumu İstanbul Çalışma ve İş Kurumu Ümraniye Hizmet Merkezi : 0216 523 90 26