What is a unit test?

Patient Tools

Read, save, and share this guide

Use these quick tools to make this medical article easier to read, print, save, or share with a family member.

On this page21 sections

Article Summary

Unit testing is the process where you test the smallest functional unit of code. Software testing helps ensure code quality, and it's an integral part of software development. It's a software development best practice to write software as small, functional units then write a unit test for each code unit. You can first write unit tests as code. Then, run that test code automatically every...

Key Takeaways

  • This article explains What is a unit test? in simple medical language.
  • This article explains What are the benefits of unit testing? in simple medical language.
  • This article explains How do developers use unit tests? in simple medical language.
  • This article explains When is unit testing less beneficial? in simple medical language.
Before reading

RX Patient Tools

Use these quick guides before reading the article, or return to them when you need help preparing questions for a doctor.

Start here Choose the right pathway for symptoms, reports, medicines, or urgent warning signs. Disease article roadmap Read this topic step by step: meaning, symptoms, warning signs, diagnosis, treatment, prevention, and follow-up. Treatment planner Prepare questions about treatment choices, benefits, risks, side effects, and follow-up. Family & caregiver guide Organize symptoms, reports, medicines, questions, and follow-up safely. Nutrition & diet guide Prepare food, hydration, supplement, and medicine-timing questions safely. Prevention guide Organize risk factors, protective habits, screening, and warning signs. Recovery guide Prepare a safe plan for activity, rehabilitation, warning signs, and follow-up.
Educational health guideWritten for patient understanding and clinical awareness.
Reviewed content workflowUse writer and reviewer profiles for stronger trust.
Emergency safety firstUrgent warning signs are highlighted below.
Definition

Unit testing is the process where you test the smallest functional unit of code. Software testing helps ensure code quality, and it’s an integral part of software development. It’s a software development best practice to write software as small, functional units then write a unit test for each code unit. You can first write unit tests as code. Then, run that test code automatically every time you make changes in the software code. This way, if a test fails, you can quickly isolate the area of the code that has the bug or error. Unit testing enforces modular thinking paradigms and improves test coverage and quality. Automated unit testing helps ensure you or your developers have more time to concentrate on coding.

What is a unit test?

unit test is a block of code that verifies the accuracy of a smaller, isolated block of application code, typically a function or method. The unit test is designed to check that the block of code runs as expected, according to the developer’s theoretical logic behind it. The unit test is only capable of interacting with the block of code via inputs and captured asserted (true or false) output.

A single block of code may also have a set of unit tests, known as test cases. A complete set of test cases cover the full expected behavior of the code block, but it’s not always necessary to define the full set of test cases.

When a block of code requires other parts of the system to run, you can’t use a unit test with that external data. The unit test needs to run in isolation. Other system data, such as databases, objects, or network communication, might be required for the code’s functionality. If that’s the case, you should use data stubs instead. It’s easiest to write unit tests for small and logically simple blocks of code.

Unit testing strategies

To create unit tests, you can follow some basic techniques to ensure coverage of all test cases.

Logic checks

Does the system perform the right calculations and follow the right path through the code given a correct, expected input? Are all paths through the code covered by the given inputs?

Boundary checks

For the given inputs, how does the system respond? How does it respond to typical inputs, edge cases, or invalid inputs?

Let’s say you expect an integer input between 3 and 7. How does the system respond when you use a 5 (typical input), a 3 (edge case), or a 9 (invalid input)?

Error handling

When there are errors in inputs, how does the system respond? Is the user prompted for another input? Does the software crash?

Object-oriented checks

If the state of any persistent objects is changed by running the code, is the object updated correctly?

Unit test example

Here is an example of a very basic method in Python and some test cases with corresponding unit test code.

Python method

def add_two_numbers(x, y):

    return x + y

Corresponding unit tests

def test_add_positives():

    result = add_two_numbers(5, 40)

    assert result == 45

def test_add_negatives():

    result = add_two_numbers(-4, -50)

    assert result == -54

def test_add_mixed():

    result = add_two_numbers(5, -5)

    assert result == 0  

What are the benefits of unit testing?

Unit testing benefits software development projects in many ways.

Efficient bug discovery

If there are any input, output, or logic-based errors within a code block, your unit tests help you catch them before the bugs reach production. When code changes, you run the same set of unit tests—alongside other tests such as integration tests—and expect the same results. If tests fail (also called broken tests) it indicates regression-based bugs.

Unit testing also helps finds bugs faster in code. Your developers don’t spend a large amount of time on debugging activities. They can quickly pinpoint the exact part of the code that has an error.

Documentation

It’s important to document code to know exactly what that code is supposed to be doing. That said, unit tests also act as a form of documentation.

Other developers read the tests to see what behaviors the code is expected to exhibit when it runs. They use the information to modify or refactor the code. Refactoring code makes it more performant and well-composed. You can run the unit testing again to check that code works as expected after changes.

How do developers use unit tests?

Developers use unit tests at various stages of the software development lifecycle.

Test-driven development

Test-driven development (TDD) is when developers build tests to check the functional requirements of a piece of software before they build the full code itself. By writing the tests first, the code is instantly verifiable against the requirements once the coding is done and the tests are run.

After completing a block of code

Once a block of code is considered complete, unit tests should be developed if they have not been already thanks to TDD. Then, you can immediately run unit tests to verify the results. Unit tests are also run as part of the full suite of other software tests during system testing. They’re typically the first set of tests that run during full system software testing.

DevOps efficiency

One of the core activities in the application of DevOps to software development practices is continuous integration and continuous delivery (CI/CD). Any changes to the code are automatically integrated into the wider codebase, run through automated testing, and then deployed if the tests pass.

Unit tests make up part of the test suite alongside integration testing. They run automatically in the CI/CD pipeline to ensure code quality as it is upgraded and changed over time.

When is unit testing less beneficial?

Unit testing isn’t always required for every single test case in every single block of code in every single project. Here are some examples of when unit testing could potentially be omitted.

When time is constrained

Even with generative unit testing frameworks, writing new unit tests takes a significant amount of your developers’ time. While input and output-based unit tests may be easy to generate, logic-based checks are more difficult.

Once your developers start writing tests, they also see refactoring opportunities in the block of code and get distracted from completing them. This can lead to extended development timelines and budget issues.

UI/UX applications

When the main system is concerned with look and feel rather than logic, there may not be many unit tests to run. Other types of testing, such as manual testing, are a better strategy than unit testing in these cases.

Legacy codebases

Writing tests to wrap around existing legacy code can prove to be near impossible, depending on the style of the written code. Because unit tests require dummy data, it can also be too time-intensive to write unit tests for highly interconnected systems with a lot of data parsing.

Rapidly evolving requirements

Depending on the project, the software can grow, change directions, or have whole parts scrapped altogether in any given work sprint. If requirements are likely to change often, there’s not much reason to write unit tests each time a block of code is developed.

What are unit testing best practices?

We give some unit testing best practices to get the most out of your process.

Use a unit test framework

It wastes time to write explicit, fully customized unit tests for every single block of code. There are automated testing frameworks for every popular programming language.

For instance, Python has pytest and unittest as two different frameworks for unit testing. Testing frameworks are used extensively throughout software development projects of all sizes.

Automate unit testing

Unit testing should be triggered on different events within software development. For example, you can use them before you push changes to a branch using version control software or before you deploy a software update.

Unit testing may also run on a complete project, set on a timed schedule. Automated unit testing ensures tests run in all appropriate events and cases throughout the development lifecycle.

Assert once

For each unit test, there should only be one true or false outcome. Make sure that there is only one assert statement within your test. A failed assert statement in a block of multiple ones can cause on which one produced the issue.

Implement unit testing

Unit testing is an important part of building software, but many projects don’t dedicate resources to it. When projects start as prototypes, are small community-based efforts, or are simply coded quickly, unit testing can be left out due to time constraints.

However, when you build projects with unit testing as a standard practice from the beginning, the process becomes far easier to follow and repeat.

What’s the difference between unit testing and other types of testing?

There are many other types of software test methods alongside unit testing. They all have specific roles to play in the software development lifecycle:

  • Integration testing checks that different parts of the software system that are designed to interact do so correctly.
  • Functional testing checks whether the software system passes the software requirements outlined before building.
  • Performance testing checks whether the software runs to expected performance requirements, such as speed and memory size.
  • Acceptance testing is when the software is tested manually by stakeholders or user groups to check whether it is working as they anticipate.
  • Security testing checks the software against known vulnerabilities and threats. This includes analysis of the threat surface, including third-party entry points to the software.

These testing methods usually require specialized tools and independent processes to check the software. Many of them are also performed after basic application functionality has been developed.

In contrast, unit tests run every time the code builds. They can be written as soon as any code is written and don’t require any special tools to run. Unit testing is considered to be one of the most basic types of software testing.

Doctor visit helper

Prepare before seeing a doctor

A simple rural-patient checklist to help you explain symptoms clearly, ask better questions, and avoid unsafe self-treatment.

Safety note: This is not a prescription or diagnosis. For severe symptoms, pregnancy danger signs, children with serious illness, chest pain, breathing difficulty, stroke-like weakness, or major injury, seek urgent care.

Which doctor may help?

Start with a registered doctor or the nearest qualified health center.

What to tell the doctor

  • Write when the problem started and how it changed.
  • Bring old prescriptions, investigation reports, and current medicines.
  • Write allergies, pregnancy status, diabetes, kidney/liver disease, and major past illnesses.
  • Bring one family member if the patient is weak, elderly, confused, or a child.

Questions to ask

  • What is the most likely cause of my symptoms?
  • Which danger signs mean I should go to hospital quickly?
  • Which tests are necessary now, and which can wait?
  • How should I take medicines safely and what side effects should I watch for?
  • When should I come for follow-up?

Tests to discuss

  • Vital signs: temperature, pulse, blood pressure, oxygen saturation
  • Basic physical examination by a clinician
  • CBC, urine test, blood sugar, or imaging only when clinically needed

Avoid these mistakes

  • Do not use antibiotics, steroid tablets/injections, or strong painkillers without proper medical advice.
  • Do not hide pregnancy, kidney disease, ulcer, allergy, or blood thinner use.
  • Do not delay emergency care when danger signs are present.

Medicine safety and first-aid guide

This section is for patient education only. It does not replace a doctor, pharmacist, or emergency care.

Safe first steps

  • Avoid heavy lifting, sudden bending, and prolonged bed rest.
  • Use comfortable posture and gentle movement as tolerated.
  • Discuss physiotherapy, X-ray, or MRI only when clinically needed.

OTC medicine safety

  • For mild back pain, pain-relief medicine may be discussed with a doctor or pharmacist.
  • Avoid repeated painkiller use if you have kidney disease, stomach ulcer, uncontrolled blood pressure, or are taking blood thinners.

Avoid these mistakes

  • Do not start antibiotics without a proper medical decision.
  • Do not use steroid tablets or injections casually for quick relief.
  • Do not delay emergency care because of home remedies.

Get urgent help if

  • Back pain with leg weakness, numbness around private area, loss of urine/stool control, fever, cancer history, or major injury needs urgent care.
Medicine names, dose, and timing must be decided by a qualified clinician or pharmacist after checking age, pregnancy, allergy, other diseases, and current medicines.

For rural patients and family caregivers

Patient health record and symptom diary

Write your symptoms, medicines already taken, test results, and questions before visiting a doctor. This note stays on your device unless you print or copy it.

Doctor to discuss: Doctor / qualified healthcare provider
Tests to discuss with doctor
  • Basic vital signs: temperature, pulse, blood pressure, oxygen level if needed
  • Relevant blood, urine, imaging, or specialist tests only after clinical assessment
Questions to ask
  • What is the most likely cause of my symptoms?
  • Which warning signs mean I should go to emergency care?
  • Which tests are really needed now?
  • Which medicines are safe for my age, pregnancy status, allergy, kidney/liver/stomach condition, and current medicines?

Emergency warning signs such as chest pain, severe breathing difficulty, sudden weakness, confusion, severe dehydration, major injury, or loss of bladder/bowel control need urgent medical care. Do not wait for online information.

Safe pathway to proper treatment

Care roadmap for: What is a unit test?

Use this simple roadmap to understand the next safe steps. It is educational and does not replace examination by a doctor.

Go to emergency care if you notice:
  • Severe or rapidly worsening symptoms
  • Breathing difficulty, chest pain, fainting, confusion, severe weakness, major injury, or severe dehydration
Doctor / service to discuss: Qualified healthcare provider; specialist depends on symptoms and examination.
  1. Step 1

    Check danger signs first

    If danger signs are present, seek emergency care and do not wait for online information.

  2. Step 2

    Record the symptom story

    Write when symptoms started, severity, medicines already taken, allergies, pregnancy status, and test results.

  3. Step 3

    Visit a qualified clinician

    A doctor, nurse, or qualified healthcare provider can examine you and decide which tests or treatment are needed.

  4. Step 4

    Do only useful tests

    Do tests after clinical assessment. Avoid unnecessary tests, random antibiotics, or repeated medicines without diagnosis.

  5. Step 5

    Follow up and return early if worse

    If symptoms worsen, new warning signs appear, or treatment is not helping, return for review quickly.

Rural patient practical tips
  • Take a written symptom diary and all previous prescriptions/test reports.
  • Do not hide medicines already taken, even herbal or over-the-counter medicines.
  • Ask which warning signs mean urgent referral to hospital.

This roadmap is for education. A real diagnosis and treatment plan requires history, examination, and clinical judgment.

Internal learning pathway

Explore related RX articles

Related guides from RX Harun are grouped to help readers move from overview to symptoms, tests, treatment, and safe next steps.

PHP, JS, CSS, Python, and Machine Learning Technology
  1. How To Speed Up a WordPress (WP) Web Site To speed up a WordPress (WP) site, you need a combination of a solid foundation (hosting, theme)…
  2. JavaScript Frameworks and Libraries List JavaScript frameworks and libraries are collections of pre-written JavaScript code designed to streamline and enhance web…
  3. Types of Linux DefinitionLinux is most widely used by advanced users who always want to have more control over…
  4. User Agents for Web Scraping DefinitionWhen scraping large amounts of information, the main problem is the risk of blocking and how…
  5. Solid-State Drive (SSD) DefinitionSolid-State Drive (SSD) is a solid-state storage device that uses integrated circuit assemblies to store data persistently,…
  6. HEADer.php Metadata DefinitionTo turn your web pages into graph objects, you need to add basic metadata to your…