golang basis - to write unit tests

Go test

Go have a built-in test instructions go testand testingpackage, but the joint is given a minimum complete test experience, the standard tool chain contains performance testing and test-based statements.

This time I intend to use Golandthe IDE to unit test

Characteristics of unit tests

  • The first and only argument must bet *testing.T
  • Function names Testbegin with, followed by a capital letter at the beginning of a word or phrase.
  • President usual method being tested so TestValidateClient
  • Call t.Erroror t.Failto indicate an error (example call t.Errorfto provide more details)
  • t.LogIt can be used to provide debugging information without fail
  • Test code must be maintained at a named something_test.gofile, for example:addition_test.go

Although I wrote this, in fact, it should be placed in the same directory, for example, the test alarm_utils.goshould be writtenalarm_utils_test.go

start testing

Test file code like the following

package main

import "testing"

func TestSum(t *testing.T) {
    tables := []struct {
        x int
        y int
        n int
    }{
        {1, 1, 2},
        {1, 2, 3},
        {2, 2, 4},
        {5, 2, 7},
    }

    for _, table := range tables {
        total := Sum(table.x, table.y)
        if total != table.n {
            t.Errorf("Sum of (%d+%d) was incorrect, got: %d, want: %d.", table.x, table.y, total, table.n)
        }
    }
}

Add a Configurationsfollows

Of course, you can also choose a folder, I have here a file is selected, choose the folder he will automatically find the line with the rules of the test file.

Then Run it wants to, can also Debug

Quote

golang basis - to write unit tests

Published 130 original articles · won praise 15 · views 50000 +

Guess you like

Origin blog.csdn.net/BTnode/article/details/104650567