Golang Test Unit Testing

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
Golang Home Unit test done well, since the need for "file name _test.go" can write unit test, and Go Test command is also very powerful, can only run a single test function, in Goland can click on the front of the Unit test function icon, But switching to Vscode requires you to do it yourself. Go Test main reference https://godoc.org/testing
input The output is consistent with the expected, the same is OK, otherwise the error.
Unit testing is a science, and there are many problems to consider, such as many boundary problems, how to automate, test samples, and so on.
Go test-run '      # Run all tests.go test-run foo     # run top-level tests matching "Foo", such as "Testfoobar". Go tes T-run foo/a=  # for top-level tests matching ' Foo ', run subtests matching ' a= '. Go test-run/a=1    # for all Top-lev El tests, run subtests matching "a=1".

  

Package Testing

import "testing"

Package testing provides support for automated testing of Go packages. It is intended to being used in concert with the ' Go Test ' command, which automates execution of any function of the form

Func testxxx (*testing. T

Where Xxx can is any alphanumeric string (but the first letter must not is in [A-z]) and serves to identify the test Routi Ne.

Within 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 this contains the TESTXXX functions as described here. Put the file in the same package as the one being tested. The file would be a excluded from regular package builds but would be a included when the ' Go Test ' command is run. For more detail, run ' Go help test ' and ' Go help Testflag '.

Tests and benchmarks May is skipped if not applicable with a call to the Skip method of *t and *b:

Func testtimeconsuming (t *testing. T) {    if testing. Short () {        t.skip ("Skipping test in short mode.")    }    ...}

Benchmarks

Functions of the form

Func benchmarkxxx (*testing. B

is considered benchmarks, and was executed by the ' Go Test ' command when Its-bench flag is provided. Benchmarks is run sequentially.

For a description of the testing flags, see https://golang.org/cmd/go/#hdr-description_of_testing_flags.

A Sample benchmark function looks like this:

Func Benchmarkhello (b *testing. B) {for    I: = 0; i < B.N; i++ {        fmt. Sprintf ("Hello")    }}

The benchmark function must run the target code B.N times. During benchmark execution, B.N is adjusted until the benchmark function lasts long enough to be timed reliably. The output

Benchmarkhello    10000000    282 ns/op

means that the loop-ran 10000000 times at a speed of 282 ns per loop.

If a benchmark needs some expensive setup before running, the timer may be reset:

Func Benchmarkbiglen (b *testing. B) {    big: = Newbig ()    B.resettimer () for    I: = 0; i < B.N; i++ {        big. Len ()    }}

If a benchmark needs to test performance in a parallel setting, it may use the Runparallel helper function; Such benchmarks is intended to being used with the Go TEST-CPU flag:

Func Benchmarktemplateparallel (b *testing. B) {    Templ: = template. Must (template. New ("Test"). Parse ("Hello, {{.}}!"))    B.runparallel (func (Pb *testing). PB) {        var buf bytes. Buffer for        PB. Next () {            buf. Reset ()            Templ. Execute (&buf, "World")        }    )}

Examples

The package also runs and verifies example code. Example functions may include a concluding line comment this begins with "Output:" and are compared with the standard OUTPU T of the function when the tests is run. (The comparison ignores leading and trailing space.) These is examples of an example:

Func Examplehello () {    fmt. Println ("Hello")    //Output:hello}func examplesalutations () {    fmt. Println ("Hello, and")    FMT. Println ("Goodbye")    //Output:    //Hello, and    //Goodbye}

The comment prefix "Unordered output:" Is like "output:", but matches any line order:

Func exampleperm () {    for _, Value: = Range Perm (4) {        FMT. Println (value)    }    //Unordered output:4    //2    //1    //3    //0}

Example functions without output comments is compiled but not executed.

The naming convention to declare examples for the package, a function F, a type T and method M on type T is:

Func Example () {...} Func Examplef () {...} Func Examplet () {...} Func examplet_m () {...}

Multiple example functions for a package/type/function/method may is provided by appending a distinct suffix to the name. The suffix must start with a lower-case letter.

Func Example_suffix () {...} Func Examplef_suffix () {...} Func Examplet_suffix () {...} Func Examplet_m_suffix () {...}

The entire test file is presented as the example if it contains a single example function in least one other function, Type, variable, or constant declaration, and no test or benchmark functions.

Subtests and Sub-benchmarks

The Run methods of T and B allow defining subtests and Sub-benchmarks, without have to define separate functions for EAC H. This enables uses like Table-driven benchmarks and creating hierarchical tests. It also provides a to share common setup and Tear-down code:

Func Testfoo (t *testing. T) {    //<setup code>    t.run ("A=1", func (t *testing). T) {...})    T.run ("a=2", func (t *testing). T) {...})    T.run ("B=1", func (t *testing). T) {...})    <tear-down Code>}

Each subtest and Sub-benchmark have a unique name:the combination of the name of the top-level test and the sequence of NA Mes passed to Run, separated by slashes, with a optional trailing sequence number for disambiguation.

The argument to The-run And-bench command-line flags are an unanchored regular expression, that matches the test ' s name. For tests with multiple slash-separated elements, such as subtests, the argument are itself slash-separated, with Expressio NS matching each name element in turn. Because It is unanchored, a empty expression matches any string. For example, using the "matching" to mean "whose name contains":

Go test-run '      # Run all tests.go test-run foo     # run top-level tests matching "Foo", such as "Testfoobar". Go tes T-run foo/a=  # for top-level tests matching ' Foo ', run subtests matching ' a= '. Go test-run/a=1    # for all Top-lev El tests, run subtests matching "a=1".

Subtests can also is used to control parallelism. A parent test would only complete once all of its subtests complete. In this example, all tests is run in the parallel with each other, and only with each other, regardless of other top-level te Sts. May defined:

Func testgroupedparallel (t *testing. T) {    for _, TC: = Range Tests {        TC: = TC//Capture range variable        t.run (TC. Name, func (t *testing. T) {            t.parallel () ...        })    }}

Run does not return until parallel subtests has completed, providing a-to-clean up after a group of parallel tests:

Func testteardownparallel (t *testing. T) {    //This Run would not return until the parallel tests finish.    T.run ("group", Func (t *testing). T) {        t.run ("Test1", ParallelTest1)        t.run ("Test2", ParallelTest2)        t.run ("Test3", ParallelTest3)    })    //<tear-down Code>}

Main

It is sometimes necessary for a test program to does extra setup or teardown before or after testing. It is also sometimes necessary for a test to control which code runs on the main thread. To the these and other cases, if a test file contains a function:

Func Testmain (M *testing. M

Then the generated test would call Testmain (m) instead of running the tests directly. Testmain runs in the main goroutine and can do whatever setup and teardown are necessary around a call to M.run. It should then call OS. Exit with the result of M.run. When Testmain is called, flag. Parse has not been run. If Testmain depends on command-line flags, including those of the testing package, it should call flag. Parse explicitly.

A simple implementation of Testmain is:

Func Testmain (M *testing. M) {//Call flag. Parse () Here if Testmain uses Flagsos. Exit (M.run ())}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.