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.
The general TDD workflow looks like this:
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 – a regular one:
…or a 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
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.