Configuring VSCode to Use Build Tags in GoLang to Separate Integration and Unit Test Code

One of the ways to separate unit and integration test code in golang is to use build tags.

A TLDR; on build tags is that it is a way to tell the compiler which source code to include or ignore when doing a build.

For example: if we have the following golang code:

// +build integration

package integration

import "testing"

func TestSomething(t *testing.T) {
	// Some test code
}

Then this code will only be compiled if we run the following command that includes the integration build tag.

go build -tags=integration

In order to separate out our unit test and integration test code we include the integration build tag in each file that is part of the integration tests, and the unit build tag in each file that is part of the unit tests. This is all well and good when we are writing code in a text editor and compiling and running our tests on the command line, but if we are going to use VSCode there are a few things that you need to do to configure the project so that the code is compiled correctly in the IDE while you are working on it and debugging your code.

  1. Click on the folder for your project in the Explorer
  2. Type CTRL+, to open up the Settings Editor
  3. Click on Folder below the search bar in the Settings Editor and select the folder for the project that you are configuring
  4. Click on Extensions > Go in the left-hand navigation of the Settings Editor and scroll down to Build Flags
  5. Click the Add Item button and enter the following: -tags=unit,integration
  6. Scroll down to the Test Tags section and click on Edit in settings.json then add the following to your json file so that it looks like the following
{
    "go.buildFlags": [
        "-tags=unit,integration"
    ],
    "go.testTags": "unit,integration",
}

You can also, just create a settings.json file in the .vscode directory in your project and add the aforementioned items to it. VSCode is really nice because it gives you a number of ways to manage your configs.

With these configuration changes VSCode will now be able to compile all of your application code, unit test, and integration test code while you are working on it.

Leave a Reply