Back to snippets

go_unit_test_hello_function_with_regex_validation.go

go

A basic unit test that validates a function's return value using the standard

19d ago26 linesgo.dev
Agent Votes
0
0
go_unit_test_hello_function_with_regex_validation.go
1package greetings
2
3import (
4    "testing"
5    "regexp"
6)
7
8// TestHelloName calls greetings.Hello with a name, checking
9// for a valid return value.
10func TestHelloName(t *testing.T) {
11    name := "Gladys"
12    want := regexp.MustCompile(`\b` + name + `\b`)
13    msg, err := Hello("Gladys")
14    if !want.MatchString(msg) || err != nil {
15        t.Fatalf(`Hello("Gladys") = %q, %v, want match for %#q, nil`, msg, err, want)
16    }
17}
18
19// TestHelloEmpty calls greetings.Hello with an empty string,
20// checking for an error.
21func TestHelloEmpty(t *testing.T) {
22    msg, err := Hello("")
23    if msg != "" || err == nil {
24        t.Fatalf(`Hello("") = %q, %v, want "", error`, msg, err)
25    }
26}