Quantum circuits need ordinary software discipline: repeatable tests, explicit expectations, and automated checks. This guide shows how to unit test quantum programs with deterministic-state assertions, probability tolerances, golden outputs, mock backends, and a CI workflow that catches regressions when gates, measurements, transpilation, or SDK versions change.
Overview
Testing a quantum circuit is not the same as testing a conventional function. A classical function usually returns one value for a given input. A circuit may produce a distribution of measurement outcomes, and hardware introduces additional variation through noise, calibration, routing, and shot sampling.
A useful quantum software testing strategy separates three questions:
- Does the circuit have the intended structure? Check qubit count, classical registers, gate placement, measurement mapping, and important resource limits.
- Does the ideal circuit produce the intended behavior? Run a statevector or exact simulator test where possible.
- Does the execution path remain acceptable? Test shot-based results, backend adapters, transpilation, and error-handling behavior separately.
This separation prevents a noisy hardware result from obscuring a simple logic error. It also makes failures easier to diagnose after a refactor or dependency upgrade. For broader resource checks, see the quantum circuit resource estimation guide.
The examples below use Python and Qiskit-style pseudocode where it is useful to be concrete. SDK APIs change, so pin the versions used by your project and confirm import paths against the installed release. The same testing principles apply in Cirq, PennyLane, and other quantum development frameworks.
What to track
1. Deterministic states and invariants
Start with circuits whose ideal result is deterministic. For example, a circuit that applies an X gate to a single qubit should produce the state corresponding to |1⟩. A Bell-state circuit should produce only the correlated outcomes 00 and 11 when measured in the computational basis.
Use exact or near-exact state assertions for this class of test. A simplified Qiskit example looks like this:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
def test_x_gate_prepares_one():
circuit = QuantumCircuit(1)
circuit.x(0)
state = Statevector.from_instruction(circuit)
probabilities = state.probabilities_dict()
assert probabilities.get("1", 0.0) == 1.0
assert probabilities.get("0", 0.0) == 0.0
For floating-point comparisons, use a tolerance rather than requiring equality. In a larger test suite, assert the property that matters instead of comparing every internal amplitude. Examples include total probability close to one, forbidden states having probability below a threshold, or two qubits having matching measurement values.
2. Probability distributions and shot-based behavior
Most application circuits are evaluated with a finite number of shots. Their counts will not match a fixed dictionary exactly, even when the circuit is correct. Test distributions using tolerances:
- Require expected outcomes to appear.
- Allow a reasonable deviation from the ideal probability.
- Check that unexpected outcomes remain below a defined ceiling.
- Use a fixed seed only when the simulator and SDK support reproducible sampling.
For a Bell-state test, you might require the combined frequency of 00 and 11 to exceed a chosen threshold, while also checking that 01 and 10 remain rare. The threshold should reflect the purpose of the test. A fast unit test can use a modest shot count; a statistical validation test can use more shots and run less frequently.
Do not hide a failing distribution test by continually widening tolerances. Record why a tolerance exists, and revisit it when the circuit, simulator, noise model, or backend changes.
3. Circuit structure and resource limits
Behavioral tests can pass even when a refactor makes a circuit much more expensive. Add structural assertions for critical circuits:
- Number of qubits and classical bits.
- Presence of required measurements and barriers, where relevant.
- Maximum depth or two-qubit gate count.
- Expected parameter names and circuit inputs.
- Correct measurement-to-classical-bit mapping.
These checks are especially useful after transpilation. A logical circuit may be unchanged while routing introduces additional swaps or decomposes gates differently. Treat depth and gate-count limits as budgets rather than universal truths: a small increase may be acceptable, but it should be visible in review. The Qiskit transpilation guide provides useful context for separating logical design from compiled output.
4. Golden outputs, used selectively
A golden output is a checked-in expected result, such as a normalized probability map, serialized circuit representation, or small set of measurement counts. Golden files are useful for snapshot-style regression testing when the output is stable and meaningful.
Keep golden outputs small and human-readable. Include the SDK version, simulator configuration, shot count, and seed when those details affect the result. Avoid snapshotting an entire transpiled circuit unless its exact form is part of the contract; compiler improvements can change harmless implementation details and create noisy diffs.
5. Backend and adapter behavior
Cloud and hardware tests should not be the only way to exercise a backend integration. Mock submission, polling, failure, timeout, and result-parsing paths in ordinary unit tests. Then reserve live-backend tests for a small integration suite.
A mock backend should return representative result shapes, including multiple circuits, missing fields, rejected jobs, and delayed completion. This catches application errors without consuming remote resources or making every pull request dependent on network availability. For simulator choices and trade-offs, see the quantum simulator comparison.
Cadence and checkpoints
Quantum test suites benefit from a regular maintenance cadence because the variables around a circuit change over time. Use the following checkpoints as a practical schedule.
Every pull request
- Run deterministic state and circuit-structure tests.
- Run fast shot-based tests with controlled simulator settings.
- Check formatting, type validation, and dependency consistency.
- Fail clearly if a resource budget is exceeded.
Monthly or quarterly
- Review pinned Qiskit, Cirq, PennyLane, simulator, and Python versions.
- Re-run golden-output tests and inspect intentional differences.
- Compare ideal-simulator results with the project’s selected noise model.
- Review flaky tests, unusually broad tolerances, and tests that have been skipped.
- Run a limited integration test against the approved backend path if the project uses one.
After a circuit or dependency change
Run the full suite after changing gate definitions, measurement logic, parameter binding, transpilation options, backend adapters, or SDK dependencies. A dependency upgrade should be treated as a test event even if application code is unchanged. Record whether a changed result reflects a corrected bug, a compiler change, a numerical difference, or an accidental regression.
For projects that reproduce published experiments, pair circuit tests with a documented verification workflow. The guide to reproducing a quantum computing research paper can help distinguish implementation checks from scientific validation.
How to interpret changes
When a test fails, first classify the failure instead of immediately changing the assertion.
- Logical regression: The circuit no longer implements the intended operation. Check gate order, qubit indexing, parameter binding, and measurement mapping.
- Statistical variation: A shot-based result moved outside its tolerance. Repeat with a fixed seed if supported, increase shots for diagnosis, and verify that the tolerance is based on a defined expectation.
- Compilation change: Transpilation produced a different depth, gate set, or qubit layout. Compare the logical circuit and compiled circuit separately.
- Numerical change: An exact comparison moved by a small floating-point amount. Replace brittle equality with an appropriate absolute or relative tolerance.
- Environment failure: The test failed because of an import, plugin, backend, or dependency issue rather than circuit behavior. Reproduce in the pinned environment before editing the circuit.
Measurement bit order deserves special attention. SDKs may display classical bits in an order that differs from the order in which qubits are described in code. A test that expects the string 01 should document which qubit maps to which classical bit. Otherwise, a correct circuit can appear to fail after a harmless refactor.
Also distinguish ideal correctness from hardware performance. Readout error, gate noise, connectivity constraints, and calibration drift can change observed counts without changing the logical algorithm. Test mitigation and noise-handling code independently; the quantum error mitigation guide covers how those layers can be compared in practice.
When to revisit
Revisit this testing workflow monthly or quarterly, and immediately after any major SDK, simulator, Python, compiler, or backend change. The goal is not to rewrite every test on a schedule. It is to confirm that the assumptions behind the tests still match the software being executed.
A minimal GitHub Actions workflow might look like this:
name: quantum-tests
on:
pull_request:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- run: python -m pip install --upgrade pip
- run: pip install -r requirements.txt
- run: pytest -q
Pin production and test dependencies in a lockfile or requirements file, and update them deliberately rather than allowing CI to resolve a different environment on every run. Keep live hardware jobs separate from pull-request tests so network access, queue time, and calibration changes do not make basic software checks unreliable.
Before closing a test-related change, verify four things: deterministic circuits have exact or tolerant state assertions, probabilistic circuits have documented distribution thresholds, backend paths have mocked failure cases, and resource changes are visible in CI. If those checks are in place, your quantum program is easier to refactor, review, and port across simulators or SDK versions. For a longer-term learning path that places testing alongside circuit construction and optimization, see the quantum computing developer roadmap.