Verilog Testbench Writing – A step by step guide
Testbenches are modules written to test a design or a part of a design by giving it different inputs and observing the output using a simulator. The testbench intends to facilitate the simulation tools by giving the required input in required order and taking the output of the simulation and checking it with the expected output.
Testbenches save a lot of design time by allowing the designer to check whether each unit functions as expected without implementing them in actual hardware. If the testbench is sufficiently advanced, each and every signal in a design can be simulated and checked using the testbench. But the complexity of the testbench increases with the complexity of the method of input required by the unit – not with the complexity of the functionality of the design. A good testbench can cover a wide range of inputs reducing the chances of the design failing in the real implementation.
Different languages and techniques such as verilog, system verilog, direct programming interface-c (DPI_C) are used for writing testbenches. For simplicity, the step by step guide uses verilog for the testbench development.
Step by step guide.
The objective of a testbench is to give the input to the unit under test (UUT) as required, take its outputs and match them with the expected output. The testbench can be non-synthesizable and need not have any synergy with a hardware design.
- Create the testbench file as a non-synthesizable top module and instantiate the UUT in it.
- Declare the registers and wires required for feeding the UUT with inputs and taking its outputs.
- Write an ‘initial begin’ block to indicate what has to be done at the begining of the simulation. This block is sequentially executed and usually contains the reset and starting the clock ticking.
- Then use always blocks to indicate the activitites that should happen continuously such as ticking the clock, feeding input and checking the output, etc.
- Input feeding can be done in different ways. An often used method is to read the inputs from the file and feeding them to the uut. The expected outptut can also be stored in a file and read out as output comes from the uut.
eg: Assume a module, ‘comparer’ used to compare the 8-bit inputs and output the largest value. Please note that the test cases for which the unit is tested are not shown in the example.
reg [7:0] input1;
reg [7:0] input2;
//Parameters to be passed (if there's any)
clk = 0; //initial value
reset = 1;
#10 reset = 0; //release reset
#5 clk != clk; //tick the clock every 5ns (clk period = 10ns)
always@(posedge clk) begin
//Arrangement for feeding the testcases go here...
if(input1 > input2) begin
if(out1 == input1) begin
$display("comparison failed! Output : %x Expected %x", out1, input1);
if(out1 == input2) begin
$display("comparison failed! Output : %x Expected %x", out1, input2);