Go language quick start (3): unit testing, problem location and code debugging

unit test

Write unit tests

In the Go language, it is supported to write unit test code for functional modules. Continue to take the calculator project built in the previous tutorial as an example. In the  package, we can write corresponding unit test code for each operation module. simplemath

The unit test file is identified by the file name suffix _test in the same directory by default. For example, we create a new file in the simplemath directory add_test.go and sqrt_test.go files, write unit tests for add.go and sqrt.go respectively. The corresponding directory structures are as follows:

Write add_test.go code 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)
    }
}

 The codes for and sqrt_test.go 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 the testing package. You can compare it to PHPUnit in PHP or JUnit in Java. We can implement automated testing based on the methods provided by this package. The format of the test method is as follows:

func TestXXX(t *testing.T) {
    // 测试逻辑
}

Run unit tests

Next, how to run these unit tests? It's also very simple.

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

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

You can see that the running results list the test content, test results and test time. If I deliberately change the code of add_test.go to this error scenario:

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 choose to execute the unit test on add_test.go and pass it in the open add_test.go file code editing area Right-click the shortcut menu and select Run 'add_test.go':

Of course, you can perform unit testing on a specific method. Click on the small green test icon that GoLand renders for the test method on the right side of the line number and select Run ‘TestAdd in calc/simplepath’:

No matter which way you run the test, you will end up with the following test failure results:

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

Problem location and debugging

Print variables

Of course, for some simple tests, you can also locate the problem by printing variables. This is usually what we do in PHP, such as through var_dump, Statements or functions such as printf, echo print the returned results. In the Laravel framework, you can also use dd or dump Method for simple and efficient variable printing debugging. In Go language, the corresponding printing function is the Printf or Println method introduced earlier, which is used to print variables Formatted output (analogous to the printf function and print function in PHP. PHP does not provide a method like Println , but you Line breaks can be achieved by appending \n to the end of the print string), both methods are located in fmt formatting In the package, we can print variables like this:

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 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 an online production environment, printing variables is not appropriate to locate the problem. At this time, we can use log The method provided by the package prints key information or error information logs to facilitate tracking of online problems. We will introduce the log function in detail in the advanced version of project management later, so you can learn about it first.

IDE debugging

If you are developing through GoLand, set breakpoints directly in the code (click the corresponding line of code), then select the source code file to be debugged, and click the option corresponding to "Debug" in the right-click drop-down menu to start debugging. Specify file code for breakpoint debugging:

After entering debugging mode, the code execution flow will be suspended 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 is , ItelliJ IDEA are almost the same:PhpStorm

GDB debugging

For daily development, it is enough to use the code debugging function that comes with GoLand. If you want to debug the code in a more Hacker way, you can choose GDB.

GDB is a powerful program debugging tool based on the command line under the Unix/Linux operating system released by the GNU open source organization. It is a binary compiled by the Go language. The file supports debugging through GDB. For example, the executable file compiled in the previous tutorial through go build calc calc can be run in debug mode directly with the following command: a> 

gdb calc

Note: This tool is not supported on Windows systems. It can be installed through the brew install gdb command on Mac.

Then, you can debug the Go code through the command line through the commands supported by GDB. You can view the code through the l command:

To jump to a certain line to view, just pass l <line> and pass in the number of lines:

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

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

This is because the Darwin kernel does not allow you to debug other processes without special permissions. Debugging a process means that you have full control over the process, so in order to prevent malicious exploitation, it is disabled by default.

To enter the next line, you can use the n command, and to print variables, you can use the p <var> command to pass in the variable name. . . I won’t go into more details on the use of more instructions, because for novices, it is not recommended to use GDB for code debugging, and it is more friendly to use GoLand.

summary

At this point, the three steps for getting started with the Go language have been completed, which are the first Go program, simple project management, unit testing and code debugging. From the next article, we will officially start to introduce the language features and object-oriented of the Go language. Advanced usage guides for programming, concurrent programming, network programming, etc.

Guess you like

Origin blog.csdn.net/weixin_59284282/article/details/125291898