5

Test Smarter, Not Harder: Harnessing Table Tests in Go

 1 year ago
source link: https://madflojo.medium.com/test-smarter-not-harder-harnessing-table-tests-in-go-f752890c2676
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.
neoserver,ios ssh client

Test Smarter, Not Harder: Harnessing Table Tests in Go

1*r54b43PAjggNrC5ENn1FNw.jpeg

I’m a big fan of testing; it is a critical part of software engineering and how reliable software gets built. I am also a big fan of making tests easier to manage and maintain. The easier a set of tests are to maintain, the more they are maintained, making them more effective.

In today’s article, I will discuss a technique popular within the Go community for simplifying repetitive tests. This technique is called Table Tests, and I will show how to use Table Tests to reduce the number of test functions while simultaneously increasing code coverage.

What are Table Tests?

Table Tests are a great way to test functions with varying inputs and results. The idea behind Table Tests is rather than writing a unique test function for each combination of input and output, a single test function can iterate over a table of function inputs and validate expected results.

Basic Greeter

To best explain the concept of Table Tests, we will first create a simple set of functions that output various greetings in different languages.

We will then use Table Tests to iterate through the multiple languages and expected greetings.

// Config is used to configure a Greeter based on desired language parameters.
type Config struct {
// Language is the language to use while greeting.
Language string
}

// Greeting returns a greeting in the language specified by the Config.
type Greeter struct {
language string
}

// New returns a new Greeter based on the provided Config.
func New(cfg Config) (*Greeter, error) {
switch cfg.Language {
case "en", "fr", "es", "de", "jp", "cn":
return &Greeter{language: cfg.Language}, nil
default:
return nil, fmt.Errorf("unsupported language: %s", cfg.Language)
}
}

// Greeting returns a greeting in the language specified by the Greeter.
func (g *Greeter) Greeting() string {
switch g.language {
case "en":
return "Hello"
case "fr":
return "Bonjour"
case "es":
return "Hola"
case "de":
return "Hallo"
case "jp":
return "こんにちは"
case "cn":
return "你好"
}
return ""
}

We must first look at the New() function to understand the example code. This function takes in a Config struct that allows users to specify a…


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK