Golang test

From 탱이의 잡동사니
Jump to navigation Jump to search

Overview

golang test 내용정리.

Basic

Package testing provides support for automated testing of Go packages. It is intended to be used in concert with the "go test" command, which automates execution of any function of the form

func TestXxx(*testing.T)

where Xxx does not start with a lowercase letter. The function name serves to identify the test routine.

With these functions, use the Error, Fail or related methods to signal failure.

To write a new test suite, create a file whose name ends _test.go that contains the TestXxx functions are described here. Put the file in the same package as the one being tested. The file will be excluded from regular package builds but will be included when the "go test" command is run. For more detail, run "go help test" and "go help testing".

A simple test function looks like this:

fund TestAbs(t *testing.T) {
  got := Abs(-1)
  if got != 1 {
    t.Errorf("Abs(-1) = %d; want 1", got)
  }
}

Testing flags

Benchmarks

Functions of the form

fund BenchmarkXxx(*testing.B)

are considered benchmarks, and are executed by the "go test" command when its -bench flag is provided. Benchmarks are run sequenctially.

A sample benchmark function looks like this <source lang=go> func BenchmarkHello(b * testing.B) {

 for i := 0; i < b.N; i++ {
   fmt.Sprintf("hello")
 }

} </source> The benchmark function must run the target code b.N times. During benchmark execution, b.N is adjusted until benchmark function lasts long enough to be timed reliably.

BenchmarkHello    10000000    282 ns/op

The above output means that the loop ran 10000000 times at a speed of 282 nsper loop.

If a benchmark needs some expensive setup before running, the timer may be reset: <source lang=go> func BenchmarkBigLen(b *testing.B) {

 big := NewBig()
 b.ResetTimer()
 for i := 0; i < b.N; i++ {
   big.Len()
 }

} </source>

TestMain


See also