Platform

Solutions

Resources

Platform

Solutions

Resources

Platform

Solutions

Resources

Blog

Loop Testing in Software Testing: Types and Examples

Abhilash

Published on

Loop testing

Table of contents

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Loops do a lot of the heavy lifting in any program, and they’re also where some of the most expensive bugs hide. Think off-by-one errors, loops that never end, edge cases that only break on the millionth pass, and exit conditions that quietly fail under load.

Loop testing is a white box technique built for exactly these problems. It hasn’t gone out of date with AI coding tools. If anything, it matters more now, because AI writes loop code faster than people can carefully review it.

Seven loop test conditions



Why Loops Need Their Own Testing

Look at where the work happens in almost any codebase: database queries, data transformations, retries, batch jobs, infinite scroll, payment reconciliation. They’re all loops. And loops are among the hardest places to find bugs, because they often fail in ways that are hard to spot, expensive to fix and difficult to reproduce from production logs.

Statement coverage tells you a line ran. Branch coverage tells you a decision went both ways. Neither tells you whether a loop works when it runs zero times, once, or right at its limit. Loop testing does.

Related Read: Statement Coverage vs Branch Coverage - Why 100% Can Still Ship a Bug



What is Loop Testing?

Loop testing is a white box testing technique that focuses on the loops in your code. It comes from classic path testing, including Boris Beizer’s book Software Testing Techniques, and has been part of mainstream software engineering guidance for decades.

The idea is simple: run every loop through a set of deliberate conditions designed to expose its bugs before production does.

There are four types of loop, and each needs a different approach:

Loop Type

What It Is

How to Test It

Simple

One loop with no other loop inside it

Use the seven test conditions

Nested

A loop inside another loop

Test one level at a time, from the inside out

Concatenated

Loops one after another in the same block

Test as simple loops if they’re independent, or as nested loops if one depends on the other

Unstructured

Loops with jumps in or out, or tangled control flow

Refactor them if you can, and if you can’t, break them into simpler shapes and test those

Treating these types as if they were all the same is one of the main ways loop bugs make it to production.



Why Loops Are Still Where Bugs Hide

Many teams find that loops cause more serious bugs than you’d expect from how much code they take up. There are a few reasons:

  • Loops carry state from one pass to the next. A bug on the 17th pass doesn’t look like a bug on the first.


  • Exit conditions are written once and tested once, even though the loop might run millions of times in production.


  • Edge cases get skipped. Zero passes, one pass and the maximum number of passes are rarely covered by happy-path tests.


  • Nested loops multiply the number of paths, and test budgets rarely keep up.


  • Performance problems hide inside correct loops and only show up at scale.


It’s a familiar story. A loop ships, it looks fine, and then it fails later, often at an awkward time, in a way that takes a senior engineer a long time to track down.

Loop bugs tend to sit at the edges, which is exactly where loop testing focuses.



How to Test Each Type of Loop


  1. Simple Loops

A simple loop is a single loop with no other loop inside it. For, while, do-while and foreach loops all count as simple loops when they’re not nested.

For a loop that can run anywhere from zero to n times, there are seven classic test conditions:

#

Condition

What It Checks

1

Skip the loop (0 passes)

The loop is skipped cleanly when there’s nothing to process

2

Run it once

The loop starts and finishes correctly

3

Run it twice

The loop moves correctly from one pass to the next

4

Run it a typical number of times (m, less than the max)

Normal day-to-day behaviour

5

Run it n − 1 times

Just under the limit

6

Run it n times (the max)

Right at the limit

7

Give it input that would need n + 1 passes

The loop handles going over the limit, for example by rejecting the input before processing anything

Here’s why this works. Zero passes test the skip path. One pass tests going in and coming out. Two passes test the handover between passes. A typical value tests normal use. The maximum and the values around it test the edge, where most loop bugs live. The classic bugs are a loop that runs once too often, one that stops one short, and one that crashes on an empty list, and these seven conditions are designed to catch all three.

Do-while loops

A do-while loop always runs at least once, because it checks the condition after the first pass. So zero passes isn’t possible, and you start from one instead.

Loops with a minimum

If a loop must run at least min times and at most max times, test min − 1 (where that’s a valid invalid input), min, min + 1, a typical value, max − 1, max and max + 1.

If there are values the loop should never take, test those too. The rule is to test every edge the loop’s spec implies, not just zero to maximum.

Worked Example: Scoring a Batch of Insurance Claims

Here’s a loop that runs through a list of pending insurance claims and gives each one a fraud score. The maximum batch size is 100 claims.

private static final int MAX_BATCH_SIZE = 100;

public List<ScoredClaim> scoreClaims(List<Claim> pendingClaims) {
    if (pendingClaims.size() > MAX_BATCH_SIZE) {
        throw new BatchTooLargeException(pendingClaims.size());
    }
    List<ScoredClaim> results = new ArrayList<>();
    for (Claim claim : pendingClaims) {
        results.add(new ScoredClaim(claim, fraudScorer.score(claim)));
    }
    return results;
}
private static final int MAX_BATCH_SIZE = 100;

public List<ScoredClaim> scoreClaims(List<Claim> pendingClaims) {
    if (pendingClaims.size() > MAX_BATCH_SIZE) {
        throw new BatchTooLargeException(pendingClaims.size());
    }
    List<ScoredClaim> results = new ArrayList<>();
    for (Claim claim : pendingClaims) {
        results.add(new ScoredClaim(claim, fraudScorer.score(claim)));
    }
    return results;
}
private static final int MAX_BATCH_SIZE = 100;

public List<ScoredClaim> scoreClaims(List<Claim> pendingClaims) {
    if (pendingClaims.size() > MAX_BATCH_SIZE) {
        throw new BatchTooLargeException(pendingClaims.size());
    }
    List<ScoredClaim> results = new ArrayList<>();
    for (Claim claim : pendingClaims) {
        results.add(new ScoredClaim(claim, fraudScorer.score(claim)));
    }
    return results;
}
private static final int MAX_BATCH_SIZE = 100;

public List<ScoredClaim> scoreClaims(List<Claim> pendingClaims) {
    if (pendingClaims.size() > MAX_BATCH_SIZE) {
        throw new BatchTooLargeException(pendingClaims.size());
    }
    List<ScoredClaim> results = new ArrayList<>();
    for (Claim claim : pendingClaims) {
        results.add(new ScoredClaim(claim, fraudScorer.score(claim)));
    }
    return results;
}

The seven conditions turn into seven tests:

Test

Claims in Batch

Expected Result

1

0

An empty list comes back, with no errors

2

1

One scored claim comes back

3

2

Two scored claims come back, each with its own score

4

50

50 scored claims come back

5

99

99 scored claims come back

6

100

100 scored claims come back

7

101

The batch is rejected, and no claims are scored

In JUnit, the first six can share one parameterised test, and the over-limit case gets its own:

@ParameterizedTest
@ValueSource(ints = {0, 1, 2, 50, 99, 100})
void scoresEveryClaimInTheBatch(int batchSize) {
    List<Claim> claims = testClaims(batchSize);
    List<ScoredClaim> results = processor.scoreClaims(claims);
    assertEquals(batchSize, results.size());
}

@Test
void rejectsBatchOverTheLimitWithoutScoringAnything() {
    List<Claim> claims = testClaims(101);
    assertThrows(BatchTooLargeException.class,
        () -> processor.scoreClaims(claims));
    verifyNoInteractions(fraudScorer);
}
@ParameterizedTest
@ValueSource(ints = {0, 1, 2, 50, 99, 100})
void scoresEveryClaimInTheBatch(int batchSize) {
    List<Claim> claims = testClaims(batchSize);
    List<ScoredClaim> results = processor.scoreClaims(claims);
    assertEquals(batchSize, results.size());
}

@Test
void rejectsBatchOverTheLimitWithoutScoringAnything() {
    List<Claim> claims = testClaims(101);
    assertThrows(BatchTooLargeException.class,
        () -> processor.scoreClaims(claims));
    verifyNoInteractions(fraudScorer);
}
@ParameterizedTest
@ValueSource(ints = {0, 1, 2, 50, 99, 100})
void scoresEveryClaimInTheBatch(int batchSize) {
    List<Claim> claims = testClaims(batchSize);
    List<ScoredClaim> results = processor.scoreClaims(claims);
    assertEquals(batchSize, results.size());
}

@Test
void rejectsBatchOverTheLimitWithoutScoringAnything() {
    List<Claim> claims = testClaims(101);
    assertThrows(BatchTooLargeException.class,
        () -> processor.scoreClaims(claims));
    verifyNoInteractions(fraudScorer);
}
@ParameterizedTest
@ValueSource(ints = {0, 1, 2, 50, 99, 100})
void scoresEveryClaimInTheBatch(int batchSize) {
    List<Claim> claims = testClaims(batchSize);
    List<ScoredClaim> results = processor.scoreClaims(claims);
    assertEquals(batchSize, results.size());
}

@Test
void rejectsBatchOverTheLimitWithoutScoringAnything() {
    List<Claim> claims = testClaims(101);
    assertThrows(BatchTooLargeException.class,
        () -> processor.scoreClaims(claims));
    verifyNoInteractions(fraudScorer);
}

Each test has a job. Test 1 catches a crash on an empty batch. Test 6 catches an off-by-one at the maximum. Test 7 checks that an oversized batch is rejected without any claims being half-processed. It’s not about writing lots of tests. It’s about each one checking something specific.


  1. Nested Loops

A nested loop is a loop inside another loop. The big problem is the number of combinations. A loop that runs n times inside one that runs m times means n × m passes. And if you try every one of the seven conditions at every level, the number of tests explodes:

Levels of Nesting

Combinations of the Seven Conditions

1

7

2

49

3

343

Testing every combination isn’t realistic, so the classic approach tests one level at a time:

  1. Start with the innermost loop: Hold all the outer loops at their minimum, and run the inner loop through its simple-loop conditions: minimum, minimum + 1, a typical value, maximum − 1 and maximum.

  2. Move out one level: Test that loop the same way, with the loops outside it at their minimum and the loops inside it at typical values.

  3. Keep going until you’ve tested the outermost loop.


As an extra risk-based step, add a few tests where every loop runs at typical or maximum values at the same time. This isn’t part of the classic method, but it samples problems that only appear when every level is busy.

This way, you catch edge bugs at every level, and you still sample the heavy combined cases, without running hundreds of tests. Where you do skip combinations, use requirements, data limits and real usage to decide which ones can’t happen, and write down why you’ve left them out.


  1. Concatenated Loops

Concatenated loops are two or more loops one after another in the same function or block. The key question is whether they’re independent.

  • Independent: the second loop doesn’t use anything the first loop changed. Test each one as a simple loop.

  • Dependent: the second loop reads something the first one changed. Test them like nested loops, paying close attention to what gets passed from one to the next.

Here’s a dependent example:

BigDecimal balance = BigDecimal.ZERO;

for (Payment payment : payments) {
    balance = balance.add(payment.getAmount());
}

for (Refund refund : refunds) {
    balance = balance.subtract(refund.getAmount());  // depends on the first loop
}
BigDecimal balance = BigDecimal.ZERO;

for (Payment payment : payments) {
    balance = balance.add(payment.getAmount());
}

for (Refund refund : refunds) {
    balance = balance.subtract(refund.getAmount());  // depends on the first loop
}
BigDecimal balance = BigDecimal.ZERO;

for (Payment payment : payments) {
    balance = balance.add(payment.getAmount());
}

for (Refund refund : refunds) {
    balance = balance.subtract(refund.getAmount());  // depends on the first loop
}
BigDecimal balance = BigDecimal.ZERO;

for (Payment payment : payments) {
    balance = balance.add(payment.getAmount());
}

for (Refund refund : refunds) {
    balance = balance.subtract(refund.getAmount());  // depends on the first loop
}

The second loop depends on balance, which the first loop builds up. Testing each loop on its own won’t catch a problem with how balance is handed over, like the first loop rounding each payment in a way that throws the refunds off. You need tests that cover both loops together, including no payments with some refunds, and some payments with no refunds.

Treating dependent loops as independent is one of the most common loop testing mistakes. Each loop works on its own, but the handover between them quietly breaks the result, and no test of either loop alone would ever catch it.


  1. Unstructured Loops

Unstructured loops have messy control flow, like jumps into or out of the loop, more than one way in, tangled goto statements, or exit logic shared with unrelated code. A normal break or continue doesn’t make a loop unstructured on its own, though you still need to test each path it creates.

The usual advice is to refactor unstructured loops into cleaner shapes. If you can’t, break the loop down into the closest simple, nested or concatenated structure, test that, and add path tests to cover the messy jumps.

Unstructured loops are usually a sign of deeper design problems that loop testing alone won’t fix. The classic guidance is that when you find them in older code, it’s better to redesign them than to just test around them.

Four Loop Types



How Loop Testing Fits with Statement and Branch Coverage

Loop testing often gets confused with coverage metrics, but it does a different job.


What It Tells You

What It Misses

Statement coverage

Each line ran at least once

How many times a loop ran

Branch coverage

Each decision went both ways

Whether the loop works at zero, one or maximum passes

Loop testing

The loop works at each of its edges

Code outside loops

A loop can have 100% statement and branch coverage from a single test that runs it three times, while the zero, one and maximum cases are never tested at all.

Loop testing is part of path testing. General path testing looks at paths across all your code. Loop testing focuses on the paths through loops, especially their edges. So coverage numbers and loop testing work together. A green coverage report doesn’t mean your loops have been tested.

For more code-level techniques like branch, path and condition coverage, see our guide to white box testing.



How to Design a Loop Test Case

A loop test isn’t just any unit test that happens to call a function with a loop in it. It needs designing on purpose, based on five things:

Input

What to Work Out

Loop type

Simple, nested, concatenated or unstructured

Loop variable

What it counts, and its full range

Exit condition

What ends the loop, and what triggers it

State

What carries over from one pass to the next

Expected results

What should be true at each edge

Then you pick the strategy for that loop type, and add clear checks at each edge: going in, coming out, and the state in between. The claims example above shows how this works, with each of the seven conditions turned into a test with a specific expected result.



How AI Coding Changes Loop Testing

Loop testing has barely changed in decades, and loops themselves haven’t either. What has changed is that AI tools now write loop code very quickly, and that code can have exactly the same edge, exit and state bugs as human-written code.

There’s an extra catch. If an AI tool writes both the code and its tests from the same wrong assumption, a subtle off-by-one or a rare exit bug can pass its own tests and still reach production.

Watch out for these three problems in AI-written loops:

Problem

What Happens

An exit condition that fails on rare input

It works for almost every input but not one rare case, so the loop runs fine in development and hangs in production when that input finally turns up

Quietly changed loop boundaries

A refactor switches the upper limit from inclusive to exclusive, or from counting from 0 to counting from 1, and regenerated unit tests don’t notice

Off-by-one errors

The loop processes one item too many or one too few

The fix is to keep your own edge-focused tests, written separately from the code, rather than letting the same tool write both the code and its tests.



Common Loop Bugs and How Loop Testing Catches Them

Loop bugs tend to follow familiar patterns, which makes them quicker to diagnose. They fall into two groups.

Classic Loop Edge Bugs

These are the bugs the seven test conditions are designed to catch:

Bug

What Happens

Which Test Catches It

Off-by-one at the end

The loop processes one item too many or too few

Max − 1, max and max + 1

Crash on an empty list

The loop assumes there’s at least one item

Zero passes

Wrong starting value

The first item is skipped or processed twice

One and two passes

Infinite loop

The exit condition is never met for some inputs

Max + 1, plus rare-input tests

State not reset

A total or flag from the last pass leaks into the next

Two passes and a typical value

Wrong inclusive or exclusive limit

< used instead of <=, or the other way round

Max − 1, max and max + 1

Bugs Made Worse by Repetition

These aren’t caused by the loop’s edges, but running something many times makes them worse. They need their own tests, like performance, load and concurrency tests:

Bug

What Happens

How to Test for It

Slowing down at scale

A database call inside the loop is fine for 10 items and far too slow for 10,000

Performance tests with realistic volumes

Memory growing every pass

Objects pile up and are never released

Long-running or soak tests

Race conditions

Two loops update shared data at the same time

Concurrency tests

Runaway retries

A retry loop keeps hammering a failing service

Tests with failing dependencies and retry limits

Timeouts

A loop that’s fine in testing takes too long with real data

Tests with production-sized data

These tables don’t cover every possible loop bug, and patterns change as languages and runtimes evolve. But the point stands: testing loops on purpose catches what ad hoc testing misses.



Where Loop Testing Meets Journey Testing

A loop can be correct in code and still wrong for the business. Take the claims scoring loop. It could run correctly, stop correctly and call the scoring function correctly, and still give customers the wrong outcome if the scoring rule itself is wrong.

So you need both:

  • Loop testing checks the code is correct inside the function.

  • Journey testing checks the customer gets the right result across the whole process.

Good teams do both on purpose. They use loop testing and other white box techniques for units and integrations. They run journey tests across the UI, APIs and database for the customer journeys those units make up. And when a loop changes, they rerun the journeys that depend on it straight away.

Code being correct has never been enough on its own to mean software works for customers. AI-written code just makes that gap more obvious.



Where Virtuoso QA Fits

Virtuoso QA doesn’t replace unit-level loop testing. It works alongside it, by checking the end-to-end journeys that loops feed into. For example, a claim submitted from start to finish, a payment reconciliation that balances, or an order that moves through every stage correctly.

Using the claims example, imagine a refactor changes the batch limit check from > to >=, so a batch of exactly 100 claims is now rejected. Your unit tests should catch that if they cover all seven conditions. But if they were regenerated alongside the code, they might not. A Virtuoso QA journey that submits a full batch of 100 claims and checks every one gets a fraud score would catch it from the customer’s side.

  • Journey tests check the screens, call the APIs and, where you’ve set it up, check the database, all in one test.

  • When a screen changes, Virtuoso QA suggests a fix for your team to approve, so journey tests keep running without being rewritten.

  • When a journey fails, you get the failure reason, screenshots and logs, which helps you work out whether the application broke or something in the test or environment changed.

So loop testing keeps the code correct, and journey testing keeps the customer result correct. As AI speeds up how fast code is written, you need both to keep up.

To see how Virtuoso QA checks customer journeys across screens, APIs and data, take a look at end-to-end testing.



A Practitioner's Checklist for Loop Testing

A short checklist captures the discipline. Apply it to loops whose failure could materially affect correctness, reliability, security, data integrity, or performance.

  • The loop type has been identified, meaning simple, nested, concatenated, or unstructured.
    ‍

  • The appropriate test strategy for the identified loop type has been documented.
    ‍

  • The boundary conditions implied by the loop's specification have been covered, including zero, one, and two iterations where applicable, a typical value, and the values around the maximum.
    ‍

  • Nested loops have been tested one level at a time, initially holding outer loops at minimum values and then holding the remaining loops at representative values.
    ‍

  • Concatenated loops have been examined for state dependency between them.
    ‍

  • Unstructured loops have been flagged for refactor or decomposed into testable parts.
    ‍

  • State carried across iterations has been validated, not assumed.
    ‍

  • The loop has been considered under concurrent invocation if reachable in production.
    ‍

  • For business-critical loop behaviour, relevant integration or customer-journey coverage exists where appropriate.
    ‍

The checklist is short by design. Loop testing fails not because the discipline is complex, but because the discipline is skipped.

Loop Testing FAQs

What is loop testing in software testing?

What are the four types of loops in loop testing?

What are the test conditions for a simple loop?

How do you test nested loops?

Is loop testing the same as branch coverage?

Why does loop testing matter with AI-written code?

Written by

Abhilash

Industry Analyst, Test Automation

Abhilash tracks how AI is reshaping software testing, from pairwise coverage to regulatory accountability, and writes research-led pieces that cut through vendor noise with numbers.

See what your next release looks like with Virtuoso

Book a walkthrough on your applications and your workflows. Bring a requirement, a user journey, or a brittle Selenium script, and watch the loop run on something you recognise.

See what your next release looks like with Virtuoso

Book a walkthrough on your applications and your workflows. Bring a requirement, a user journey, or a brittle Selenium script, and watch the loop run on something you recognise.

See what your next release looks like with Virtuoso

Book a walkthrough on your applications and your workflows. Bring a requirement, a user journey, or a brittle Selenium script, and watch the loop run on something you recognise.

Virtuoso QA is establishing the standard of proof for software releases. Its governed QA loop turns business requirements into tests for any browser-based application: AI proposes, a deterministic engine executes, a person approves what matters, and every decision leaves evidence.

Trust Center

AICPA

SOC

WAVE STRONG PERFORMER

@ Copyright 2026 SpotQA, Creators of Virtuoso QA

Virtuoso QA is establishing the standard of proof for software releases. Its governed QA loop turns business requirements into tests for any browser-based application: AI proposes, a deterministic engine executes, a person approves what matters, and every decision leaves evidence.

Trust Center

AICPA

SOC

WAVE STRONG PERFORMER

@ Copyright 2026 SpotQA, Creators of Virtuoso QA

Virtuoso QA is establishing the standard of proof for software releases. Its governed QA loop turns business requirements into tests for any browser-based application: AI proposes, a deterministic engine executes, a person approves what matters, and every decision leaves evidence.

Trust Center

AICPA

SOC

WAVE STRONG PERFORMER

@ Copyright 2026 SpotQA, Creators of Virtuoso QA