Table Driven Approach In Unit Testing

What is Table Driven Approach?

A table driven approach uses tables to classify the different kind of entities, aiming at a reduction of the number of cases requiring distinct code.

Consider writing a code for a particular feature that has a variety of uses. For example, assume you require a calculator that can perform addition, subtraction, multiplication, and division..

Consider that your calculator can perform operations with several digits, such as the sum of two numbers, the total of three numbers, etc…

Now you need to write unit test cases for different scenario,
A general approach to write the unit test cases for multiple scenario, deals with the different kind of entities using case statement or extented if-then-else statement, and disadvantage is, if in future some more functionality or code will be added, then again we need to write multiple if-then-else statement, which is bit difficult to manage everytime.

Consider Below Example:

result.js
result.test.js (Normal Approach)

As you can see in above image result.test.js , a unit test case file, it’s written in general/standard approach, now if we need to add one more case in result.js for checking if someone has obtained than 75% marks. In order to test the functionality again we need add one more it('',()=>{} condition and so on….everytime we need to add it block for new scenario.

Disadvantage with this approach are:

  1. Your unit test cases file will be getting longer everytime you will add new scenario.
  2. Difficult to Maintain, as your test cases file has too many lines.

Let’s write same unit test cases for result.js file with Table Driven Approach

result.test.js (Using Table Driven Approach)

In above image, you can see, you just need to update input values in tests object, and as you don’t need to worry about output logic everytime, It’s easy to mainatain.

Output results for test cases :

Output

That’s all 😀

One thought on “Table Driven Approach In Unit Testing

Leave a comment