Press "Enter" to skip to content

Go Quick Start (III): Unit Testing, Problem Locating and Code Debugging

unit testing

Write unit tests

In Go language, it supports writing unit test code for function modules, and continues to use The first tutorial For example, in the simplemath In the package, we can write corresponding unit test code for each calculation module.

Unit test files are suffixed by the file name in the same directory by default _test As a sign, for example, we simplemath New under directory add_test.go and sqrt_test.go Files, respectively add.go and sqrt.go Write unit tests. The corresponding directory structure is as follows:

 -w634

to write add_test.go The codes are as follows:

 package simplemath import "testing" func TestAdd(t *testing. T) { r := Add(1, 2) if r != 3 { t.Errorf("Add(1, 2) failed. Got %d, expected 3.", r) } }

as well as sqrt_test.go The codes are as follows:

 package simplemath import "testing" func TestSqrt(t *testing. T) { v := Sqrt(9) if v != 3 { t.Errorf("Sqrt(9) failed. Got %v, expected 3.", v) } }

When writing unit tests, you need to introduce testing Package. You can compare it to PHP unit in PHP or JUnit in Java. We can implement automated testing based on the methods provided by the package. The format of the test method is as follows:

 func TestXXX(t *testing. T) { //Test logic }

Run unit tests

Next, how to run these unit tests? This is also very simple.

In GoLand, you can select the package to execute unit tests, such as simplemath , and then select Run ->go test simplicity through the right-click shortcut menu:

 GoLand performs unit tests on the specified package

You can see the test run results in the Run window at the bottom of GoLand:

 GoLand unit test passed

As you can see, the running results list the test content, test results and test time. If I deliberately add_test.go The error scenario is changed to:

 func TestAdd(t *testing. T) { r := Add(1, 2) if r != 2 { t.Errorf("Add(1, 2) failed. Got %d, expected 3.", r) } }

Then we execute the unit test again. This time, we can directly select add_test.go Execute the unit test in the opened add_test.go In the file code editing area, right-click the shortcut menu and select Run 'add_test. go'

 GoLand performs unit tests on specified files

Of course, you can specifically test a method by clicking the small green test icon that GoLand renders for the test method on the right of the line number, and selecting Run 'TestAdd in calc/simplepath':

 GoLand performs unit tests on the specified method

No matter how the test is run, the following test failure results will be obtained in the end:

 GoLand unit test failed

The printed error message is very concise, but it is enough for developers to quickly locate the file and line number of the problem code, so as to confirm whether it is a unit test problem or a program problem in the shortest time.

Problem location and debugging

Print Variables

Of course, for some simple tests, you can also locate problems by printing variables. Usually, we do this in PHP, for example, by var_dump printf echo Such statements or functions can also print the returned results through dd or dump Method to perform simple and efficient variable printing debugging. In the Go language, the corresponding printing function is introduced previously Printf or Println Method, used to format the output of variables (analogous to the printf Functions and print Function. PHP does not provide similar functions Println This method, but you can add \n To implement line break), both methods are located in fmt In the format package, we can print variables as follows:

 fval := 110.48  ival := 200  sval := "This is a string. "  fmt.Println("The value of fval is", fval)  fmt.Printf("fval=%f, ival=%d, sval=%s\n", fval, ival, sval)  fmt.Printf("fval=%v, ival=%v, sval=%v\n", fval, ival, sval)

The corresponding output result is:

 The value of fval is 110.48 fval=110.480000, ival=200, sval=This is a string.  fval=110.48, ival=200, sval=This is a string.

Output Log

If the code is executed in the online production environment, printing variables is not suitable for locating problems. At this time, we can use log The method provided by the package is to print key information or error information logs to facilitate tracking online problems. We will introduce the log function in detail later in the advanced version of engineering management, so you can understand it here first.

IDE debugging

If you are developing through GoLand, set breakpoints directly in the code (click the corresponding code line), select the source code file to debug, and click the option corresponding to Debug in the right-click drop-down menu to start breakpoint debugging of the specified file code:

 GoLand code debugging

After entering debug mode, the code execution process will pause at the breakpoint. In the Debug window of the console below the GoLand interface, you can see the stack information of the current program. You can debug the code through manual control (jump in, jump out, enter the next line, terminate debugging, etc.). The specific operation mode and PhpStorm ItelliJ IDEA:

 -w1093

The GoLand official blog also has an introductory tutorial: https://blog.jetbrains.com/go/2019/02/06/debugging-with-goland-getting-started/ If you are interested, you can take a look.

GDB debugging

It is enough to use the code debugging function provided by GoLand for daily development. If you want to debug the code in a more hacker way, you can choose GDB.

GDB It is a powerful command line based program debugging tool under Unix/Linux operating system released by GNU Open Source Organization. Binary files compiled with Go language support debugging through GDB, such as the previous tutorial through go build calc Compiled executable file calc , you can directly run in debug mode with the following commands:

 gdb calc
 GDB code debugging

Note: Windows system does not support this tool, Mac can use brew install gdb Command installation.

Then, you can debug the Go code in the command line way through the instructions supported by GDB l Command View Code:

 GDB code debugging

To jump to a line to view the passed l <line> Number of incoming lines:

 GDB code debugging

To set a breakpoint for a line, you can use the b <line> To achieve:

 GDB code debugging

Then through run Command to run the program. If it is on a Mac system, the following error may be reported:

 GDB code debugging

This is because the Darwin kernel does not allow you to debug other processes without special permission. Debugging a process means that you have full control over the process, so it is prohibited by default to prevent malicious use. allow gdb The best way to control other processes is to sign them with a certificate trusted by the system. For the corresponding solution, see here: https://opensource.apple.com/source/lldb/lldb-69/docs/code-signing.txt Solutions corresponding to Chinese )。

Enter the next line and use n Command, print variable can be used p <var> The instruction passes in the variable name... I won't go further with more instructions, because for beginners, GDB is not recommended for code debugging. It's more friendly to use GoLand directly, isn't it? If you want to explore more uses of GDB debugging, please see Corresponding official documents

Summary

So far, the three steps of zero foundation introduction to Go language have been completed, which are the first Go program, simple project management, unit testing and code debugging. From the next chapter, we will formally introduce the language features, object-oriented programming, concurrent programming, network programming and other advanced use guides of Go language WeChat official account Follow the update of this series of tutorials. If you have any questions during the learning process, you can use the comments below the tutorials or add " Go Language Seminar "Discuss with Xuejun.

4 Comments

  1.  Laragh
    Laragh January 30, 2021

    I'd better be honest and use AliCloud's Linux to run GDB. Running gdb on Mac is risky

Post reply