Original post

Test-Driven Development, or as it is commonly referred to, is the development process in which tests are written first, then the code to support them is created, and, when every test passes, code is refactored.

Let’s have a look at how the unique of allow us to be proficient with this workflow.

The general TDD workflow looks like this:

Write tests

Let’s start by writing some tests by navigating to any test file, e.g. tdd_test.go

To generate the tests, we can use the Generate feature (Alt+Insert on Windows/Linux or Cmd+N on macOS).

TDD in GoLand - 01 - generate menu

Here, we can choose the type of test we want to create – a regular one:

TDD in GoLand - 02 - Create Regular Test

…or a table- approach:

TDD in GoLand - 03 - Generate Table Test

Moving forward, I’ll use the table-testing approach, as it makes it easy to add test cases and keeps my code nice and tidy.

Once our test cases are added, our code should look like this:

TDD in GoLand - 04 - Test cases

Run tests to see that they fail

Using the Run context configuration (Ctrl+Shift+F10 on Windows/Linux or Ctrl+Shift+R on macOS) will run our tests.

TDD in GoLand - 05 - Run tests without code

Normally, tests should fail now, but we are not making any assertion that can fail, so, the Go tool will report this as a pass.

As such, let’s move to the next step, generate some code and see the results.

Write the code and make it pass the tests

Given we don’t execute anything in the tests yet, let’s add the basic code in place.

TDD in GoLand - 06 - Add code that fails

Many people like running tests automatically on changes, especially when doing TDD, so let’s enable that option in the IDE as well.

TDD in GoLand - 07 - Toggle automatic running of tests

The next step is to implement our code and see how it makes our tests fail:

TDD in GoLand - 08 - Add good code and make tests pass

Refactor the code

With the code in place and working, it’s time to move it to a non-test file and clean it up a bit. This is where the IDE’s refactorings such as Move, Rename, and others come into place.

First, let’s move the code to a different file:

TDD in GoLand - 09 - Move code to non-test file

Then, let’s do a bit of renaming and cleanup:

TDD in GoLand - 10 - Refactoring and code cleanup

Throughout these refactorings, we can see that the tests still pass, which hopefully increases our trust in the automated refactorings that the IDE performs on our behalf.

This concludes our short article on how to use GoLand for TDD in Go, and beyond. Please share your feedback in the comments section below, in our issue tracker, or tweet us at @GoLandIDE.