How to Write Unit Tests for Quantum Circuits Across Qiskit, Cirq, and PennyLane
quantum software testingunit testingQiskitCirqPennyLanequantum circuits

How to Write Unit Tests for Quantum Circuits Across Qiskit, Cirq, and PennyLane

QQubit365 Editorial Team
2026-11-13
7 min read

A practical checklist for testing quantum circuits across Qiskit, Cirq, and PennyLane before simulation or hardware execution.

Reliable quantum programming starts with testing circuits before they reach a simulator or hardware backend. This checklist shows how to verify state preparation, gate behavior, measurement probabilities, parameterized circuits, shot-based results, and regressions across Qiskit, Cirq, and PennyLane.

Overview

A quantum circuit unit test should answer a narrow question with a reproducible expectation. Does the circuit prepare the intended state? Does an X gate flip the computational basis state? Do measured probabilities stay within an acceptable range? Does changing a parameter produce the expected trend? These questions are more useful than testing whether a circuit merely executes without raising an error.

The most dependable workflow separates exact tests from statistical tests. Statevector or wavefunction simulations can validate amplitudes and ideal gate behavior with strict numerical tolerances. Shot-based simulation and hardware runs produce samples, so their results should be checked against probability ranges rather than exact counts. Keeping these test types separate makes failures easier to diagnose.

Use a small test circuit first, then apply the same structure to larger algorithms. A useful test suite generally contains:

  • Construction tests: confirm that the expected qubits, classical bits, gates, measurements, and parameters exist.
  • Behavior tests: verify simple input-output cases such as basis-state flips and Bell-state correlations.
  • Probability tests: compare sampled measurement frequencies with expected distributions.
  • Parameterized tests: check known angles, boundary values, and a small selection of intermediate values.
  • Regression tests: preserve important outputs so refactoring or SDK upgrades cannot silently change circuit behavior.

The exact assertion helpers and simulator interfaces change between SDK releases. Treat the examples below as patterns to adapt to the version used by your project, and pin dependencies in continuous integration. For broader workflow guidance, see How to Test and Debug Quantum Programs.

Checklist by scenario

1. Test state preparation and gate behavior

Begin with deterministic basis states. A circuit that prepares the zero state should return a statevector with probability one on the all-zero basis state. Applying an X gate to one qubit should move that probability to the corresponding one state. For a two-qubit circuit, test each qubit independently where practical; this catches incorrect wire order and register-index assumptions.

In Qiskit, an ideal statevector test can follow this pattern:

from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector


def test_x_gate_maps_zero_to_one():
    circuit = QuantumCircuit(1)
    circuit.x(0)
    state = Statevector.from_instruction(circuit)
    assert abs(state.probabilities()[1] - 1.0) < 1e-10

The equivalent Cirq test can inspect the final state from a simulator:

import cirq
import numpy as np


def test_x_gate_maps_zero_to_one():
    qubit = cirq.LineQubit(0)
    circuit = cirq.Circuit(cirq.X(qubit))
    result = cirq.Simulator().simulate(circuit)
    probabilities = np.abs(result.final_state_vector) ** 2
    assert np.isclose(probabilities[1], 1.0, atol=1e-10)

With PennyLane, return probabilities from a QNode and compare the relevant entry:

import pennylane as qml


def test_x_gate_maps_zero_to_one():
    dev = qml.device('default.qubit', wires=1)

    @qml.qnode(dev)
    def circuit():
        qml.PauliX(wires=0)
        return qml.probs(wires=0)

    probabilities = circuit()
    assert abs(float(probabilities[1]) - 1.0) < 1e-10

These tests are deliberately simple. They establish the meaning of qubit indexing and basis-state ordering before you test a larger algorithm.

2. Test measurement probabilities and correlations

Superposition and entanglement require statistical checks. A Hadamard gate on one qubit should produce approximately equal zero and one probabilities in an ideal simulator. A Bell-state circuit should produce correlated 00 and 11 results, with little or no probability assigned to 01 and 10.

For shot-based tests, use a tolerance that reflects the number of shots and the purpose of the test. A practical assertion might require each expected probability to remain within a chosen absolute tolerance, while also checking that the distribution sums to one. Avoid asserting exact counts unless the circuit is deterministic.

A Bell-state test should normally verify two properties:

  1. The combined probability of the expected outcomes is high enough.
  2. The probability of forbidden outcomes is low enough.

This is more robust than checking only the most common bit string. A broken circuit can still produce the expected dominant result while introducing an unacceptable error rate in the remaining samples.

3. Test parameterized circuits

Parameterized circuits need tests at meaningful points, not just one arbitrary parameter value. For a rotation, include values that should produce a known basis state, a balanced superposition, and the inverse or opposite operation. Also test the parameter binding path separately from the circuit mathematics.

For example, a rotation test can check that an angle of zero leaves the state unchanged, while a suitable quarter-turn produces the expected probability pattern. Use a table-driven test where the framework supports it:

cases = [
    (0.0, 0.0),
    (expected_angle, expected_probability),
]

for angle, expected in cases:
    actual = run_parameterized_circuit(angle)
    assert abs(actual - expected) < tolerance

The placeholder values should be derived from the gate convention used by your SDK. Do not copy expected values from another framework without checking rotation definitions, wire order, and measurement conventions.

4. Add cross-framework regression tests

When the same circuit is implemented in Qiskit, Cirq, and PennyLane, compare an agreed behavioral contract rather than internal objects. The contract might define the number of qubits, supported inputs, expected probabilities, parameter meanings, and measurement-bit order.

Run each implementation on an ideal simulator first. Normalize output labels before comparison because frameworks can display multi-qubit bit strings in different orders. Then compare probabilities or expectation values within a documented tolerance. The circuit-porting checklist is useful when wire mapping or measurement conventions differ.

What to double-check

  • Qubit and bit order: Confirm which qubit is the least significant bit and how counts or samples are formatted.
  • Measurement placement: A circuit returning a statevector is not the same as one containing measurement operations. Test the intended execution path.
  • Exact versus sampled output: Statevector amplitudes can use tight numerical tolerances; shot-based results need statistical tolerances.
  • Randomness: Set a seed when the SDK and simulator support it, but do not make correctness depend on one random sample.
  • Parameter binding: Verify that every parameter is bound once, in the intended order, and with the expected units.
  • Transpilation: Test both the logical circuit and, where relevant, the transpiled circuit. Optimization may change gate counts without changing the intended result.
  • Backend differences: An ideal simulator test cannot prove that a circuit will behave identically on hardware. Hardware tests should use acceptance ranges and record backend configuration.
  • Resources: Track qubit count, depth, gates, and shots so tests remain affordable and interpretable. Use the quantum circuit resource estimation guide when a test grows substantially.

For hardware-oriented validation, keep functional tests distinct from noise studies. Readout mitigation, zero-noise extrapolation, and symmetry checks can help analyze noisy results, but they should not conceal a basic circuit-construction error. See Quantum Error Mitigation Techniques for that separate layer of evaluation.

Common mistakes

Testing only that execution succeeds. A circuit can compile and run while applying gates to the wrong wires. Assert observable behavior, not just the absence of exceptions.

Using exact equality for floating-point results. Statevector and expectation-value calculations can differ by small numerical amounts. Use an absolute tolerance, and add a relative tolerance when values vary in scale.

Expecting fixed counts from a probabilistic circuit. A valid 50/50 circuit will not produce identical counts on every run. Test a range, and choose shot counts that make the range meaningful.

Ignoring label order. The string 01 may refer to a different qubit ordering in another framework. Include a small basis-state test that documents the convention before comparing larger circuits.

Overfitting tests to one simulator. If production uses hardware or a different provider, include a backend-appropriate test stage. Keep ideal tests fast, and reserve slower integration tests for the pipeline stage that needs them.

Updating SDKs without reviewing tests. An SDK upgrade can alter imports, result objects, transpilation defaults, or measurement APIs. Read release notes, run the full suite, and investigate changed results rather than widening tolerances immediately.

When to revisit

Revisit this checklist whenever you add a gate, change qubit mapping, introduce parameters, modify measurement handling, or optimize a circuit. It should also be part of the review process before sending a new circuit to cloud quantum computing hardware.

Run the complete suite when upgrading Qiskit, Cirq, PennyLane, a plugin, a simulator, or a backend integration. Recheck tests after porting a circuit between frameworks, changing transpilation settings, or moving from statevector simulation to shot-based execution. These changes can expose differences that were invisible in a single ideal test.

A practical final checklist is:

  1. Write one deterministic state-preparation test.
  2. Write one gate-behavior test for each critical operation or subroutine.
  3. Check probabilities or correlations for every measured algorithm output.
  4. Test parameter boundaries and at least one intermediate value.
  5. Use statistical tolerances for shots and document how they were chosen.
  6. Normalize qubit and bit ordering before comparing SDK implementations.
  7. Run fast ideal tests in continuous integration and separate hardware tests from unit tests.
  8. Record SDK, simulator, backend, seed, shots, and tolerance settings for reproducibility.

Unit testing will not remove the uncertainty of quantum hardware, but it can remove a large class of avoidable software errors. Build the tests around observable behavior, keep assumptions explicit, and update them whenever the circuit, SDK, or execution environment changes.

Related Topics

#quantum software testing#unit testing#Qiskit#Cirq#PennyLane#quantum circuits
Q

Qubit365 Editorial Team

Quantum Computing Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.