Writing a Testbench
Poke your design, watch it, and prove it works
You have built circuits. Now you need to test them. A testbench is a separate Verilog file whose only job is to feed inputs into your design and watch the outputs. It is never turned into hardware - it is a test rig that lives only in simulation.
The parts of a testbench
- It has no ports - it is the top of the world, nothing connects to it.
- It creates signals to wire into your design (the DUT, "Design Under Test").
- It generates a clock and drives the inputs over time.
- It prints or checks the outputs.
A testbench for the counter from lesson 7
module counter_tb;
reg clk = 0;
reg rst = 1;
wire [3:0] count;
// Connect the design under test
counter dut (.clk(clk), .rst(rst), .count(count));
// Clock: flip every 5 time units -> a 10-unit period
always #5 clk = ~clk;
// Stimulus: what to do, and when
initial begin
$dumpfile("wave.vcd"); // record a waveform
$dumpvars(0, counter_tb); // 0 = record all signals, every level below counter_tb
rst = 1; #12; // hold reset a bit
rst = 0; #100; // let it count
$display("final count = %d", count);
$finish; // end the simulation
end
// Print every change
initial $monitor("t=%0t rst=%b count=%d", $time, rst, count);
endmoduleThe simulation-only helpers you just used
| Construct | What it does |
|---|---|
| initial | Runs once at time zero - used only in testbenches |
| #5 | Wait 5 time units (the delay) |
| $display | Print a line once, like printf |
| $monitor | Auto-print whenever a listed signal changes |
| $finish | Stop the simulation |
| $dumpfile / $dumpvars | Record a waveform you can view |
The # delays, initial, and the $ system tasks work in simulation only. They are how you build tests, but a synthesis tool ignores or rejects them - they never become hardware. That separation is exactly right: real circuits have no "wait 5 units" button.
See the waveform
On EDA Playground, tick "Open EPWave after run" and press Run. You will see clk ticking and count climbing 0,1,2,3 and wrapping at 15. On your own machine with Icarus Verilog, run iverilog then vvp, then open wave.vcd in GTKWave. Watching the waveform is how you build real intuition for what your hardware does over time.
A self-checking testbench beats reading printouts by eye. Instead of just $display, compare against what you expected and print PASS or FAIL. As designs grow, you cannot eyeball thousands of values - which is exactly why Design Verification became its own discipline. The next path covers that.