Building a SystemVerilog Testbench from Start to Finish
Build a runnable testbench: instantiate the DUT, generate clock and reset, apply scenarios, check outputs, and finish with a trustworthy verdict.
A self-checking testbench connects stimulus to an expected result and a verdict. It must also detect stalls and terminate without requiring manual waveform inspection.
The driver applies stimulus. The monitor reconstructs observed exchanges. An independent reference model predicts results, and the scoreboard compares the two paths.
Define the counter contract
The DUT pulse_counter is a four-bit counter:
| Port | Role |
|---|---|
i_clk | the counter acts on each rising edge |
i_rst_n | active-low asynchronous reset |
i_enable | the counter advances at 1 and holds at 0 |
o_count | 4-bit result, wrapping from 4'hF to 4'h0 |
The contract already identifies reset, hold, consecutive counting, and wraparound from 15 to zero. Predict results from those rules rather than reading the DUT's internal registers.
Set connections and time units
The test module has no ports. It instantiates the DUT, declares connections, and generates the clock:
module pulse_counter_tb;
timeunit 1ns;
timeprecision 1ps;
localparam time CLK_PERIOD = 10ns;
logic clk = 1'b0;
logic rst_n = 1'b0;
logic enable = 1'b0;
logic [3:0] count;
pulse_counter dut (
.i_clk (clk),
.i_rst_n (rst_n),
.i_enable (enable),
.o_count (count)
);
always #(CLK_PERIOD / 2) clk = ~clk;
endmoduletimeunit and timeprecision define local timing. Named connections withstand port-order changes. Inputs start known, with reset asserted.
This skeleton and the complete version below are alternatives declaring the same module. Do not compile both declarations together.
Run automatic comparisons
module pulse_counter_tb;
timeunit 1ns;
timeprecision 1ps;
localparam time CLK_PERIOD = 10ns;
logic clk = 1'b0;
logic rst_n = 1'b0;
logic enable = 1'b0;
logic [3:0] count;
int unsigned checks = 0;
int unsigned errors = 0;
pulse_counter dut (
.i_clk (clk),
.i_rst_n (rst_n),
.i_enable (enable),
.o_count (count)
);
expected follows the functional requirement; its four-bit width models modulo 16. step_and_check separates scenarios from driving details. Check counts, errors, a final report, and the watchdog expose runs without a valid verdict.
Separate driving from sampling
The DUT runs at rising edges; this bench drives and checks at falling edges. Checks therefore see completed nonblocking updates from the previous rising edge. This convention needs revision for a falling-edge DUT or multiple clocks.
=== includes X and Z. Since the expected value is known, an unknown observed bit fails the check. This procedural check can stop immediately:
assert (count === expected)
else $fatal(1, "count=%h expected=%h", count, expected);$error allows continued checks and grouped diagnostics; $fatal marks final failure. Assertions used as checkers must be enabled in the simulator configuration.
Centralize timing in an interface
A clocking block specifies timing for a richer protocol:
interface counter_if(input logic clk);
logic rst_n;
logic enable;
logic [3:0] count;
clocking tb_cb @(negedge clk);
default input #1step output #0;
output rst_n, enable;
input count;
endclocking
modport dut (
input clk, rst_n, enable,
output count
);
modport tb (clocking tb_cb);
endinterfaceWait on @(bus.tb_cb), drive bus.tb_cb.enable <= ..., and read bus.tb_cb.count. input #1step samples just before the edge; output #0 drives at that edge using clocking-block rules. Direct signal access bypasses this synchronization. Check simulator support.
In a class-based environment, a module keeps the DUT and clock, an interface groups signals, and classes use a virtual interface. A supported program automatic can hold scenarios, but it cannot contain always processes. Coordinate tasks and draining before its initial blocks finish.
Adding #0 or #1 to selected lines does not solve every race. The former does not order threads; the latter depends on time units. An explicit timing convention states the actual requirement.
Adapt checks for combinational logic
A combinational DUT needs no clock or reset. Allow its events to settle before comparing:
task automatic check_add(
input logic [7:0] lhs,
input logic [7:0] rhs
);
logic [8:0] expected;
a = lhs;
b = rhs;
expected = {1'b0, lhs} + {1'b0, rhs};
#1ns;
assert (sum === expected)
else $error("a=%0d b=%0d sum=%0d expected=%0d",
lhs, rhs, sum, expected);
endtaskThe delay belongs in the testbench and must cover relevant simulated delays. It should not be added to RTL.
Finish and diagnose
A watchdog must allow a normal run while detecting stalls promptly. In a layered bench, stop generation, drain accepted transactions, then check pending expectations and counts.
A VCD trace helps explain failures:
initial begin
$dumpfile("pulse_counter.vcd");
$dumpvars(0, pulse_counter_tb);
endFor this simple bench, enable Icarus SystemVerilog mode and select the top module:
iverilog -g2012 -Wall -s pulse_counter_tb -o simv pulse_counter.sv pulse_counter_tb.sv
vvp simvPackages and interfaces must precede their users in file lists. Before trusting the verdict, check widths, reset, initialization, sampling times, and boundary scenarios. Waveforms support the automatic verdict rather than replace it.
📝 Test your knowledge - Chapter quiz