SoFunction
Updated on 2025-03-05

Summary of golang test usage example

Testing package serves automated testing

Basic Test

Table Drvien Test

Table-based tests test the input and expected output of each case through table form to test the correctness of the program

func TestFib(t *) {
    var fibTests = []struct {
        in       int // input
        expected int // expected result
    }{
        {1, 1},
        {2, 1},
        {3, 2},
        {4, 3},
        {5, 5},
        {6, 8},
        {7, 13},
    }
    for _, tt := range fibTests {
        actual := Fib()
        if actual !=  {
            ("Fib(%d) = %d; expected %d", , actual, )
        }
    }
}
  • Skip the test
    • SkipNow(): Skip the test
    • Skip(): Skip the test and output the log
    • Skipf(): Skip the test and format the output log
  • Failed but continued
    • Fail(): Mark the test failed, but continue execution
    • FailNow(): Mark the test failed, no execution will continue
    • Error(): Mark the test failed and output
    • Errorf(): Mark the test failed and format the output
  • Output
    • Log(): Output
    • Logf(): Format output
  • Failed and interrupted
    • Fatal(): equivalent to FailNow() + Log()
    • Fatalf(): equivalent to FailNow() + Logf()

Parallel()

Parallel method indicates that it will be executed in parallel with other tests with Parallel method.

ExampleXXX()

If the ExampleXXX method containsOutput: The line comment at the beginning will compare the output with the value in the comment during the run test.

If it is an uncertain order, you canUnordered output: As the beginning

But without such annotation, this is a normal function that cannot be run directly

Stress test

Stress testing methodfunc BenchmarkXXX(*)Function name display.

The function body format is as follows

func BenchmarkHello(b *) {
    for i := 0; i < ; i++ {
        // do sth
    }
}

The stress test will be automatically adjusted for a long enough time

Reset the timer

If you want to skip time-consuming work that does not require timekeeping, you can use()Reset the timer

Parallel testing

If you want to parallel stress tests, you can passRunParallelaccomplish

func BenchmarkHelloParallel(b *) {
  (func(pb *) {
    // do sth
  })
}

Memory statistics

ReportAllocsMethod to turn on memory statistics function

The output result will become the following form

// Method name      Total number of iterations                                                                                                                     �
BenchmarkHello        2000000           898 ns/op         368 B/op           9 allocs/op

Custom metric values

ReportMetric(n float64, unit string)Report custom metrics

  • If the measure is for each iteration, you should divide it by
  • By convention, the unit should end with "/op".
  • ReportMetricAny previously reported value for the same unit will be overwritten. If the unit is an empty string, or the unit contains any spaces,ReportMetricWill cause panic.
  • If the unit is the unit that is usually reported by the benchmark framework itself (such as "allocs/op"),ReportMetricThis measure is overwritten.
  • Setting "ns/op" to 0 will disable this built-in metric.
(func(b *) {
		var compares int64
		for i := 0; i < ; i++ {
			s := []int{5, 4, 3, 2, 1}
			(s, func(i, j int) bool {
				compares++
				return s[i] < s[j]
			})
		}
		// This metric is per-operation, so divide by  and
		// report it as a "/op" unit.
		(float64(compares)/float64(), "compares/op")
		// This metric is per-time, so divide by  and
		// report it as a "/ns" unit.
		(float64(compares)/float64(().Nanoseconds()), "compares/ns")
	})

Sub-test

Sub-tests can be tested in tests. Sub-tests can share common operations such as initialization and can be used as necessary operations before the parent test is executed.

func TestSubTest(t *) {
	("sub1", func(t *) {
		("sub1")
	})
	("sub2", func(t *) {
		("sub2")
	})
	("sub3", func(t *) {
		("sub3")
	})
}

Fuzzy test

The fuzzy test method is namedfunc FuzzXXX(f *)

func FuzzReverse(f *) {
  	// Add use cases to seed corpus for fuzz testing    testcases := []string{"Hello, world", " ", "!12345"}
    for _, tc := range testcases {
        (tc)  // Use  to provide a seed corpus
    }
  	// Fuzz testing is performed.  For parameters of type string, a random string will be generated  	// The Reverse method in this test is reversible, so it can be verified by two retrograde operations to verify its correctness    (func(t *, orig string) {
        rev := Reverse(orig)
        doubleRev := Reverse(rev)
        if orig != doubleRev {
            ("Before: %q, after: %q", orig, doubleRev)
        }
        if (orig) &amp;&amp; !(rev) {
            ("Reverse produced invalid UTF-8 string %q", rev)
        }
    })
}

Running fuzzy tests havego testandgo test -fuzzTwo ways, the former will only run manually added use cases, while the latter will generate data randomly

It is worth noting that if a use case with running errors after go test -fuzz is executed, it will still execute the use case in the corpus file even if the next time you execute go test.

Ref

/doc/tutorial/fuzz

https:///The-Golang-Standard-Library-by-Example/chapter09/09.

This is the end of this article about golang testing. For more related golang testing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!