Test Driven Development with GoLand
Test-Driven Development, or TDD 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 features of GoLand allow us to be proficient with this workflow.
The general TDD workflow looks like this:
- write tests
- run tests to see that they fail
- write the code and make it pass the tests
- refactor the code
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).
Here, we can choose the type of test we want to create – the classic type of test:
… or a test using the table-testing approach:
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:
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.
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.
Many people like running tests automatically on changes, especially when doing TDD, so let’s enable that option in the IDE as well.
The next step is to implement our code and see how it makes our tests fail:
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:
Then, let’s do a bit of renaming and 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.