Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging tests with delve

I'm using "go test -v" to run bunch of unit tests. I'd like to debug them using delve. When I try to run debugger, I get an "Can not debug non-main package" error. So, how can I debug unit tests using delve debugger ?

like image 608
SpiderRico Avatar asked Apr 12 '17 22:04

SpiderRico


People also ask

What is delve debugger?

Delve is a debugger for the Go programming language. The goal of the project is to provide a simple, full featured debugging tool for Go. Delve should be easy to invoke and easy to use. Chances are if you're using a debugger, things aren't going your way.

How do I run in debug mode?

If you use VS Code to run your Go code and have the official Go extension installed on the editor, you can debug your code by pressing F5 or Run and Debug on your computer.

How do you add a breakpoint in Golang?

Set line breakpointsClick the gutter at the executable line of code where you want to set the breakpoint. Alternatively, place the caret at the line and press Ctrl+F8 .


2 Answers

Use dlv test:

$ dlv test -- -test.v
Type 'help' for list of commands.
(dlv) continue
=== RUN   TestReadFileError
--- PASS: TestReadFileError (0.00s)
=== RUN   TestReadFile
--- PASS: TestReadFile (0.00s)
[..]
PASS
Process 8014 has exited with status 0
(dlv) quit
Process 8014 has exited with status 0

You can also pass -test.run to select tests to run (just like go test -run).

Internally, this is the same as Flimzy's answer (it compiles the test binary with go test -c), but more streamlined and won't leave .test files for you to clean up.

like image 150
Martin Tournoij Avatar answered Oct 04 '22 03:10

Martin Tournoij


I'm not familiar with delve, but if it can work on a compiled binary, just compile your tests using the -c flag:

    -c
        Compile the test binary to pkg.test but do not run it
        (where pkg is the last element of the package's import path).
        The file name can be changed with the -o flag.

Then run delve on the output.

like image 38
Flimzy Avatar answered Oct 04 '22 03:10

Flimzy