Blog

Test cases: how to write them, with a template and examples

A test case states the setup, the steps, the input and the result a feature must give. How to write one, which cases to write, a template and examples.

A test case is one check written down so that anyone can run it and get the same verdict. It says what must be true before you start, what to do, which data to use and what the software should do in response. If the software does something else, the case fails, and the failure points at one behavior rather than at “the booking page is broken”.

This guide covers what goes into a test case, how it differs from a test scenario, a test script and a test suite, a template you can copy, and how to decide which cases to write so that a small set catches the defects a large, careless one would miss. Where testing fits as a whole is in our explainer on what software testing is. The definitions and techniques here follow the ISTQB Foundation Level syllabus in its version 4.0.1, the curriculum behind the ISTQB Certified Tester Foundation Level exam.

The examples all come from one imaginary product: the booking site of a lakeside campground, where visitors pick a site, choose dates and party size, pay, and can cancel later. None of it is real: the campground, its rules and every number were made up to illustrate the techniques.

What is a test case?

In the ISTQB process, testers first work out what to test. Those items are test conditions: a rule, a requirement or a risk that needs checking. They then work out how to test each one, and that is where test cases come from. The syllabus describes test design as “elaborating the test conditions into test cases”, together with the test data and environment the cases need.

A test case therefore sits between a requirement and a run. The campground’s rule “a site holds up to six people” is a test condition. “Try to book a site for seven people and check that the booking is refused with a message” is a test case. The case is concrete enough to run without guessing, and its expected result is stated before anyone runs it, so the verdict cannot be bent to fit whatever happened.

A useful test case has four qualities:

  • One behavior. It checks one thing, so a failure tells you what broke.
  • Repeatable. Another person, or a tool, gets the same verdict from the same starting point.
  • A stated expected result. “The page works” is not a result. “The booking is refused and the message ‘A site holds up to 6 people’ appears under the People field” is.
  • Traceable. It names the requirement or risk it checks, so you can see which rules have no case and which cases test rules that no longer exist.

Test case, test scenario, test script and test suite

These terms often get swapped for one another, along with two more that sit beside them in the table. They differ, and the difference matters when you are agreeing what a team will deliver.

Term What it is Campground example
Test condition Something that needs checking, taken from a requirement, a risk or an acceptance criterion A site holds up to six people
Test scenario A situation or user goal written in a line, usually covered by several cases. A common working term rather than one the ISTQB syllabus defines; its nearest relative there is the test condition A family books a site for a weekend
Test case Preconditions, steps, input data and the expected result for one check Book for seven people; the booking is refused with a message
Test procedure Test cases put in the order they are run, with any setup between them Create a booking, then change it, then cancel it
Test script The instructions for running a test, written for a person (manual) or as code a tool runs (automated) A Playwright file that fills the form and checks the message
Test suite A set of test procedures or scripts run together All booking checks run before each release

The syllabus links them in one sentence: “Test cases can be organized into test procedures, which are often assembled into test suites.” The same stage produces the scripts, written for people or as code. A test case is also different from a use case. A use case describes how a user reaches a goal with the system (“a visitor books a campsite”); one use case usually needs many test cases, covering the normal path, the alternatives and the errors.

What goes in a test case

Teams name the fields differently, and the syllabus notes that organizations vary a lot in how they shape and name their test documents. The fields below appear in nearly every format because each one answers a question the person running the case would otherwise have to ask.

Field What it holds Why it is there
ID A unique reference, such as TC-013 Lets defect reports, results and requirements point at it
Title The behavior checked, in a short sentence Tells a reader what fails when this case fails
Requirement or risk The rule, story or acceptance criterion it checks Traceability: which rules are covered, and what to update when one changes
Priority High, medium or low, or a number Decides what runs first when time is short
Preconditions The state the system and data must be in before step 1 Most "cannot reproduce" arguments come from an unstated starting point
Test data The exact values to use "A large party" gives two testers two different tests
Steps Numbered actions, one per line Anyone can run the case the same way
Expected result What the software must do, stated before the run The pass or fail rule
Postconditions The state the system should be left in Shows what later cases can rely on, and what needs cleaning up
Actual result, status What happened, pass or fail, date, build, tester Recorded at each run, not when the case is written

The last row belongs to the run rather than to the case. A case is written once and run many times, so keeping its results in a separate log, or in a test management tool, avoids a case document that is rewritten every week.

A test case template

Copy this block into a document, a spreadsheet row or a ticket. Square brackets are the parts to fill in.

ID:               [TC-000]
Title:            [The behavior checked, in one sentence]
Requirement:      [Story, rule or acceptance criterion this checks]
Priority:         [High / Medium / Low]
Preconditions:    [State of the system, accounts and data before step 1]
Test data:        [Exact values, or where to find them]
Steps:            1. [Action]
                  2. [Action]
                  3. [Action]
Expected result:  [What the software must do, observable and specific]
Postconditions:   [State the system is left in]
-- filled in at each run --
Build / date:     [Version tested, date]
Actual result:    [What happened]
Status:           [Pass / Fail / Blocked], defect [ID if failed]

Filled in for the campground, a negative case looks like this:

ID:               TC-013
Title:            A booking for more people than a site holds is refused
Requirement:      BK-4 "A site holds 1 to 6 people"
Priority:         High
Preconditions:    Lakeshore site 12 is free for the chosen nights.
                  The visitor is signed out.
Test data:        Arrival 30 days from today, 2 nights, 7 people
Steps:            1. Open the page for Lakeshore site 12.
                  2. Enter the arrival date and 2 nights.
                  3. Enter 7 in People.
                  4. Select Check availability.
Expected result:  "A site holds up to 6 people" appears under People.
                  No Reserve button is shown and no hold is placed.
Postconditions:   Site 12 is still free for those nights.

Two details in it are deliberate. The arrival date is relative (“30 days from today”), because a fixed date turns into a past date and the case starts failing for a reason that has nothing to do with the software. And the expected result checks what did not happen (no hold placed) as well as the message, since a booking page that shows the right warning and still holds the campsite would fail visitors just as badly.

How to write test cases, step by step

  1. Start from the test basis. Gather what says how the software should behave: requirements, user stories and their acceptance criteria, designs, and the answers to questions you have asked. A case can only be as precise as the rule behind it, so unclear rules are the first findings, before any test runs.
  2. List the test conditions. Write each rule or risk as one line: party size limits, stay length limits, refund rules, what a visitor may do after paying. Rank them by risk. A wrong refund costs more than a misaligned label.
  3. Choose a technique for each condition. Number ranges call for partitions and boundaries, combinations of rules for a decision table, and anything with a status for state transitions. The next section shows each one on the campground. The technique decides how many cases you need and which values they use.
  4. Write the cases. One behavior each, with preconditions, exact data, numbered steps and an expected result a stranger could judge. Write the positive cases first, then the negative ones. The syllabus gives the same order for cases derived from acceptance criteria, followed by non-functional qualities such as speed and usability.
  5. Link every case to its condition. A simple table of requirement against case IDs shows the gaps. The syllabus puts it plainly: tracing test cases to requirements “can verify that the requirements are covered by test cases”.
  6. Have someone else read them. A developer or the product owner reading the cases will spot a wrong expected result before it costs a run. This is also the cheapest moment to find that two people understood a rule differently.
  7. Run, record and maintain. Log the actual result against the build. When a rule changes, the trace from step 5 shows which cases to update or retire.

Which test cases to write: four design techniques

Writing every possible case is impossible: a party-size field alone accepts thousands of values. Test design techniques pick a small set that still finds the likely defects. The syllabus says they help testers “develop a relatively small, but sufficient, set of test cases in a systematic way”. These four are black-box techniques. They work from the specified behavior, not the code, so the cases stay useful when the code is rewritten.

Equivalence partitioning

Split the possible values into groups the software should treat the same way, then test one value from each group. The reasoning, in the syllabus’s words, is that if one value from a partition finds a defect, any other value from it should too, so “one test for each partition is sufficient”.

For the campground’s People field (rule BK-4: 1 to 6 people):

Partition Values Valid? One test value
Too few 0 or fewer Invalid 0
Allowed 1 to 6 Valid 4
Too many 7 or more Invalid 9
Not a number Letters, blank Invalid "four"

Four cases cover the field. Invalid partitions count as much as the valid one: coverage here means every partition, including the ones that should be refused, exercised at least once. When a form has several fields, a case can cover a partition from each field at once. The simplest rule for that, which the syllabus calls Each Choice coverage, asks only that each partition of each field is used at least once, without testing every combination.

Boundary value analysis

Defects gather at the edges of ranges, where a developer writes “less than” instead of “less than or equal to”. Boundary value analysis tests the edges of each ordered partition. In the two-value version, each boundary value is tested with its nearest neighbor in the next partition. In the three-value version, it is tested with both neighbors, which can catch a wrongly written condition that the two-value version lets through.

For 1 to 6 people, taking the edges of the allowed range, 1 and 6, as the boundary values:

  • Two-value: 0, 1, 6 and 7.
  • Three-value: 0, 1, 2, 5, 6 and 7.

Which values to test for a People field that allows 1 to 6 people. A number line from 0 to 9 has three partitions: 0 or fewer is invalid, 1 to 6 is valid, 7 or more is invalid. Equivalence partitioning tests one value from each partition, for example 0, 4 and 9. Two-value boundary value analysis tests 0, 1, 6 and 7. Three-value boundary value analysis adds 2 and 5, the inside neighbors of each boundary.

The same thinking applies to the stay length (1 to 14 nights in the invented rules, so 0, 1, 14 and 15) and to dates, where the edges are today, the last bookable day and the day after it.

Decision table testing

When the outcome depends on a combination of conditions, list the conditions and outcomes in a table and test each feasible column. The campground’s invented refund rule has two conditions:

Condition or outcome Rule 1 Rule 2 Rule 3
Canceled within 24 hours of booking? Yes No No
Seven or more days before arrival? Any Yes No
Full refund X
Refund less a $10 fee X
First night kept, rest refunded X

Two yes-or-no conditions give four combinations. When the booking is canceled within 24 hours, the arrival date makes no difference, so those two combinations merge into Rule 1 and the table has three columns. That gives three test cases, one per column. The table also does a second job: it shows gaps in the rule. Writing it out raises the question nobody had asked, which is what happens to a visitor who books five days ahead and cancels an hour later. The table says Rule 1, a full refund. If the campground meant otherwise, the rule changes before the code is written.

State transition testing

Anything with a status (an order, an account, a booking) can be drawn as states and the events that move it between them. A campground booking might go like this:

From Event To
Held Payment made within 10 minutes Confirmed
Held 10 minutes pass without payment Expired
Confirmed Visitor cancels Canceled
Confirmed Visitor arrives Checked in
Checked in Visitor leaves Completed

Each test case is a sequence of events. Three cases cover all five valid transitions: hold, pay, arrive and leave; hold and let the time run out; hold, pay and cancel. Then test what should not be possible, such as canceling a booking that is already checked in, or paying for one that has expired. The syllabus advises one invalid transition per test case, so that one defect cannot hide another.

These four are not the only techniques. White-box techniques derive cases from the code itself, and experience-based techniques, such as error guessing and exploratory testing, use the tester’s knowledge to find what the specification never mentioned. A good set usually mixes all three.

Test case examples

The same rule can be written three ways, depending on who will read or run it.

As a written case for a person to run, like TC-013 above. This suits checks that need judgment, checks run rarely, and early work on a feature that still changes every week.

As a scenario in Given/When/Then form, which business people can read and some tools can run. The Gherkin language used by Cucumber has a Scenario Outline that, in Cucumber’s own documentation, “is run once for each row in the Examples section”, so the boundary values from earlier become one readable block:

Scenario Outline: Party size limits on a campsite
  Given Lakeshore site 12 is free for 2 nights starting 30 days from today
  When a visitor asks to book it for <people> people
  Then the booking is <outcome>

  Examples:
    | people | outcome  |
    | 0      | refused  |
    | 1      | offered  |
    | 6      | offered  |
    | 7      | refused  |

Cucumber’s documentation recommends three to five steps per example, which keeps each scenario about one behavior.

As an automated test script, which a tool runs on every change. Here is TC-013 written for Playwright, a browser testing tool whose documentation describes its tests as ones that “perform actions and assert the state against expectations”. The address is a placeholder.

import { test, expect } from '@playwright/test';

test('TC-013: a booking for 7 people is refused', async ({ page }) => {
  const day = 24 * 60 * 60 * 1000;
  const arrival = new Date(Date.now() + 30 * day).toISOString().slice(0, 10);

  await page.goto('https://campground.example/sites/lakeshore-12');
  await page.getByLabel('Arrival').fill(arrival);
  await page.getByLabel('Nights').fill('2');
  await page.getByLabel('People').fill('7');
  await page.getByRole('button', { name: 'Check availability' }).click();

  await expect(page.getByText('A site holds up to 6 people')).toBeVisible();
  await expect(page.getByRole('button', { name: 'Reserve' })).toHaveCount(0);
});

The steps are the same as in the written case, and the script checks what a browser can see: the message and the missing Reserve button. Confirming that no hold was placed takes one more check against the booking system. Playwright and Cucumber are examples of their kind, not a recommendation. Automated scripts pay off for checks that run on every release, such as a smoke test after each deploy or the regression suite that guards features that already work.

Types of test cases

Test cases are grouped in several ways at once, so one case can belong to more than one group.

  • Positive and negative. A positive case confirms the software does what it should with valid input (a party of four books a site). A negative case confirms it refuses or handles what it should not accept (a party of seven, a blank date, a card that is declined).
  • Boundary cases. The edge values from boundary value analysis. They are often negative cases too.
  • Functional and non-functional. Functional cases check what the software does. Non-functional cases check how well it does it: speed under load, usability, accessibility, security.
  • By test level. Unit cases check one piece of code, integration cases check pieces working together, system cases check the whole product, and acceptance cases check it against what the users and the business agreed. The levels themselves are explained in levels of testing.
  • By purpose in a release. Regression cases recheck what already worked after a change, smoke cases confirm a new build is fit to test at all, and user acceptance testing cases are run by the software’s future users.
  • Manual and automated. The same case can start as a written check and later become a script.

Choosing which cases run first

There is rarely time to run every case before every release, so cases carry a priority. The syllabus lists three common ways to set the order:

  • By risk: cases covering the most important risks run first. On the campground, payment and refunds come before the photo gallery.
  • By coverage: cases that exercise the most code run first.
  • By requirement: cases tracing to the requirements the business ranks highest run first.

Order is limited by dependencies. If a high-priority case needs a booking that a lower-priority case creates, the lower one has to run first. Availability matters too: a case that needs a payment provider’s test environment can run only when that environment is up.

Weak test cases and how to fix them

Weak Why it fails Better
"Check that booking works." No data, no steps, no result: two testers run two different tests One case per behavior, such as TC-013, with exact data and a stated result
Expected result: "An error is shown." Any error passes, including the wrong one Name the message, where it appears, and what must not happen
Preconditions missing The case passes on one tester's machine and fails on another's State the accounts, data and settings needed before step 1
One case checks the price, the email and the refund The first failure hides the rest, and the defect report is vague Split it into one case per behavior
A fixed date such as June 12 The case breaks once the date has passed Relative dates: "30 days from today"
Steps copied from the code The case confirms what was built, not what was asked for Write cases from the requirement, ideally before the code exists
Cases nobody has updated since the rules changed Failures are ignored as "the old behavior" Trace cases to requirements and retire or update them when a rule changes

Questions people ask

What is an example of a test case?

A test case for a booking form: with a free campsite and a signed-out visitor, enter an arrival date 30 days ahead, 2 nights and 7 people, then select Check availability. Expected result: the message “A site holds up to 6 people” appears and no booking hold is placed. The full version, with its ID, requirement and postconditions, is TC-013 in the template section above.

Is it a test case or a testcase?

Two words. The ISTQB syllabus writes “test case” throughout, as two words, and most testing documents follow it. “Testcase” as one word turns up mostly in code, where names cannot contain spaces.

How many test cases are enough?

Count by coverage, not by a number. Decide which coverage you need for each condition (every partition, every boundary, every column of a decision table, every valid transition), then write the cases that reach it. Riskier features deserve stricter coverage. The syllabus notes that covering every transition, including attempts at invalid ones, should be the minimum for mission and safety-critical software.

Who writes test cases?

Usually testers, but not only them. In acceptance test-driven development, cases are written before the feature is built, by people with different viewpoints: customers, developers and testers. Developers write the unit test cases for their own code. The product owner’s part is often the most valuable: reading the expected results and saying whether they match what the business wants.

What is the difference between a test case and a use case?

A use case describes how a user reaches a goal with the system, from the user’s side: a visitor finds a free site, books it and pays. A test case is one check of one behavior along that path or off it: a party of seven is refused, a declined card leaves the site free, an expired hold releases the site. One use case typically needs many test cases.

Before the first case is written

The quality of a set of test cases is decided mostly before anyone writes one, by how clear the rules are. On a project of your own, it is worth asking early:

  • Is each rule written down with its numbers and edges, such as “1 to 6 people”, rather than “small groups”?
  • Who decides the expected result when a rule is unclear, and how fast can they answer?
  • Will the cases be traced to the requirements, so you can see what is covered?
  • Which checks will be automated to run on every release, and which stay manual?
  • Will you be able to read the cases and their results?

If a website or web platform is what you are planning, our custom web development page describes what that service covers. Send your questions through the contact page and a member of the team will reply within one business day.

The full service behind this post: Custom Web Development Services.

Ready to scope your project?

Send us two sentences about what you need. We reply within one business day with the next step and any questions we need answered first.

Get a Quote