Detailed explanation of go basics 2-go run & test

一 go run

Compile and run a main package (package). The commonly used running methods are as follows:

go run .
go run hello
go run is followed by a path, and all go source files under this path (excluding sub-paths) belong to the main package.

==go run filename1 filename1 ==
go run is followed by go source files. These source files must belong to the main package (package), and all source files required by the program must be listed.

However, in module-aware mode, the above method is not applicable. The go run command is run in the directory where the main package is located.
go run .orThe file name where the go run main function is located

Second, go test

Go has a lightweight unit testing framework that can easily test related functions. You need to pay attention to the following points when using this testing framework:

1. Generally, the test file and the tested file are in the same directory, or they may not be in the same directory;

2. When in the same directory, if the package where the tested file is located is fmt, then the package where the test file is located must be fmt_test, otherwise an error will be reported;

S C:\Users\love1\Documents\technology\go\gopathMode\hello\yyzc> go test -v .\greetings_test.go
#command-line-arguments
greetings_test.go:5:8: found packages greet (greetings.go) and greet1 (greetings_test.go) in C:\Users\love1\Documents\technology\go\gopathMode\hello\yyzc
FAIL command-line-arguments [setup failed]
FAIL

3. The test file needs to end with _test.go;

4. Test files generally contain functions named similarly to TestXXX. The go test framework will run these functions in sequence. Examples of these functions are as follows;

func TestXXX (t *testing.T){
    
    
}

Otherwise, the following error will be reported

:\Users\love1\Documents\technology\go\gopathMode\hello\yyzc\greetings_test.go:8:1: wrong signature for TestHello, must be: func TestHello(t *testing.T)
FAIL command-line-arguments [setup failed]
FAIL
PS C:\Users\love1\Documents\technology\go\gopathMode\hello\yyzc>

5. Execution method

go test .Execute all test files in the current directory
go test directoryExecute all test files in the yyzc directory
go test filenameOnly execute the specified test file

Guess you like

Origin blog.csdn.net/qq_41768644/article/details/132778432