Module 1010 min

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

verilog
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);
endmodule

The simulation-only helpers you just used

ConstructWhat it does
initialRuns once at time zero - used only in testbenches
#5Wait 5 time units (the delay)
$displayPrint a line once, like printf
$monitorAuto-print whenever a listed signal changes
$finishStop the simulation
$dumpfile / $dumpvarsRecord a waveform you can view
Pro tip

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.

Watch out

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.