3

Table driven tests in Go

 1 year ago
source link: https://www.ardanlabs.com/blog/2023/01/table-driven-tests-in-go.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Table driven tests in Go

Author image

Cheikh Seck

January 19, 2023

Introduction

Table tests are a great way to test different inputs and associated outputs for a function in Go. To write a table test, you define a slice of some data struct with fields of the input data you’ll need and the expected outcome. Then you can loop through this slice and pass the data stored for each element to your function. One disadvantage of table tests is as the data set in your slice grows, the harder it is to find the failing case. Luckily, Miki will share some tips to manage this with the Go test suite.

In this video, Miki has a large set of input data to test. Miki will write sub-tests to make it easier to identify a failing case. To execute a sub-test, Miki will invoke the Run method from the testing.T parameter provided to every test function. During invocation, he’ll pass a test name and a function with test logic to execute. If the test fails, the test name Miki passed earlier is displayed on the console making it easier to find the failing case. Watch and learn how to add sub tests to your code.

Things you will learn in this video

  • What constitutes a table test?
  • Importance of table tests.
  • Implementing sub tests with Go.

Video


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK