Running and Debugging Unit Tests with Flags in VS Code
To run unit tests with flags in VS Code, one can modify the go.testFlags value in the vscode settings.json file. However, the issue encountered here is the different configurations required for running and debugging tests.
Running Tests
To run tests with the required flag, the following configuration can be used:
<code class="json">"go.testFlags": [ "-ldflags", "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn" ]</code>
Debugging Tests
For debugging tests, the configuration should include single quotes around the flag:
<code class="json">"go.testFlags": [ "-ldflags", "'-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'" ]</code>
Combined Configuration
To avoid switching between configurations, one can try the following combined configuration:
<code class="json">"go.testFlags": [ "-ldflags", "'-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'", "-ldflags", "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn"" ]</code>
Using Dlv for Debugging
Alternatively, one can use dlv to debug tests. To compile the test binary with optimizations disabled:
go test -c -ldflags "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn" -gcflags="all=-N -l"
Start a headless dlv session:
dlv exec ./foo.test --headless --listen=:2345 --log --api-version=2 -- -count=1 -- $(pwd)/some/path
Connect VS Code to the dlv session by creating a launch.json file:
<code class="json">{ ... "configurations": [ { "name": "Debug Test", "type": "go", "request": "attach", "mode": "remote", "port": 2345, "host": "127.0.0.1", "showLog": true, "trace": "log" } ] }</code>
The above is the detailed content of How to Run and Debug Unit Tests with Flags in VS Code?. For more information, please follow other related articles on the PHP Chinese website!