Go Testing: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 73: Line 73:
=TO DEPLETE=
=TO DEPLETE=
<font color=darkkhaki>
<font color=darkkhaki>
==Writing a Unit Test==


* Tests are identified as functions starting with <tt>Test_...</tt> and taking an argument <tt>(t *testing.T)</tt>.
<pre>
package blue
import "testing"
func TestBlue(t *testing.T) {
    ...
    t.Error("expected this, got ", ...)
}
</pre>
Then
<pre>
go test
</pre>


The command will look for any tests in any of the files in the current folder and run them.
The command will look for any tests in any of the files in the current folder and run them.

Revision as of 02:11, 16 September 2023

External

Internal

Overview

Go comes with a lightweight test framework that includes the go test command and the testing package. The tests live in *_test.go files.

Write a Unit Test

Write a module as shown here:

Declaring a Module

For each file containing behavior to test (a.go)

package a

func Reverse(s string) string {
 rs := []rune(s)
 var result []rune
 for i := len(rs) - 1; i >= 0; i-- {
  result = append(result, rs[i])
 }
 return string(result)
}

add a <file-name>_test.go test file. In this case a_test.go. These files are ignored by the compiler and only compiled and executed when go test is run.

The test file should be part of the same package.

The test file should import testing:

package a

import "testing"

func TestReverseEmptyString(t *testing.T) {
 expected := ""
 result := Reverse("")
 if result != expected {
  t.Errorf("expected %q, got %q", expected, result)
 }
}

func TestReverseOneCharString(t *testing.T) {
 expected := "a"
 result := Reverse("a")
 if result != expected {
  t.Errorf("expected %q, got %q", expected, result)
 }
}

func TestReverseTwoCharString(t *testing.T) {
 expected := "ba"
 result := Reverse("ab")
 if result != expected {
  t.Errorf("expected %q, got %q", expected, result)
 }
}

From the module directory, run the tests:

go test

PASS ok example.com/a 0.116s

TO DEPLETE


The command will look for any tests in any of the files in the current folder and run them.

Also see external test packages.

TODO testing idiom "Introducing Go" page 96.