Golang testing: Difference between revisions

From wikinotes
No edit summary
No edit summary
Line 21: Line 21:
<blockquote>
<blockquote>
The builtin go test framework is fairly minimalist.<br>
The builtin go test framework is fairly minimalist.<br>
Tests are just functions, you can loop them if useful,<br>
Tests are just functions, you can loop them if useful.<br>
And you can use the following tools to evaluate tests:


<syntaxhighlight lang="go">
Tests are typically kept alongside code.
func TestHello(t *testing.T) {
    // log message and fail (but continue executing)
    t.Errorf("An expectation was not satisfied")
    t.Fail()        // mark test as failed, but continue
    t.FailNow()      // mark test as failed and stop executing
 
    t.Skip("Reason") // log, and stop executing
 
    t.TempDir()      // provides a tempdir that is deleted once test finishes running
}
</syntaxhighlight>


<syntaxhighlight lang="go">
<syntaxhighlight lang="go">
Line 62: Line 50:
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Example -->
</blockquote><!-- Example -->
= Assertions =
<blockquote>
There are no assertions, you are responsible for tests and messages.
<syntaxhighlight lang="go">
func TestHello(t *testing.T) {
    // log message and fail (but continue executing)
    t.Errorf("An expectation was not satisfied")
    t.Fail()        // mark test as failed, but continue
    t.FailNow()      // mark test as failed and stop executing
    t.Skip("Reason") // log, and stop executing
    t.TempDir()      // provides a tempdir that is deleted once test finishes running
}
</syntaxhighlight>
</blockquote><!-- Assertions -->

Revision as of 21:53, 6 June 2022

Go ships with a test suite.

Documentation

testing https://pkg.go.dev/testing@go1.18.3

Usage

go test -run      # run all tests
go test -run Foo  # run top-level tests containing 'Foo'

Example

The builtin go test framework is fairly minimalist.
Tests are just functions, you can loop them if useful.

Tests are typically kept alongside code.

// myproject/mypackage/mylib.go

package mypackage

func Hello(name string) string {
    return "Hello, " + name
}
// myproject/mypackage/mylib_test.go

package mypackage

import "testing"

func TestHello(t *testing.T) {
    res := Hello("Adam")
    if res != "Hello, Adam" {
        t.Errorf("Hello() result did not match")
    }
}

Assertions

There are no assertions, you are responsible for tests and messages.

func TestHello(t *testing.T) {
    // log message and fail (but continue executing)
    t.Errorf("An expectation was not satisfied")
    t.Fail()         // mark test as failed, but continue
    t.FailNow()      // mark test as failed and stop executing

    t.Skip("Reason") // log, and stop executing

    t.TempDir()      // provides a tempdir that is deleted once test finishes running
}