TDD is a great way to approach software development. There are many reasons for this, but mostly it enables you to think about functionality that you require in small testable code, and match the acceptance requirements for each functionality. Also in the long run having great test coverage ensures that each new code does not break other functionality.

In go all test functions start with the word Test. You usually get two values with error being the second value.

You can write tests like this:

1
2
3
4
5
6
func TestNewTask(t *testing.T) {
_, err := NewTask("")
if err == nill {
t.Errorf("expected 'empty title', got nil")
}
}

You can run the tests with the go tool using go test or go test [name of package] or go test [name of package] ... which includes all the tests inside the project.

Or run tests while coding with watch like:

1
2
3
4
Watch -t go test
PASS
ok github.com/kkarimi/todo/task 0.017s
2017-04-29 12:02:33...

Best way to approach TDD is to imagine the smallest component of your application, for example this would be a Task in a Todo application, and slowly create functions that can save, find/return, update and delete it. These tests functions would begin as structure, returning nil, until it is their turn to fully work.

Here is an example of a small todo app with tests.

I hope to explore this more with a REST and GraphQL API in TDD. It’s important to note that on larger projects API with TDD use test-utilities and helpers provided by web frameworks. Django for example has great testing tools which the book Test-Driven Development with Python… covers in depth.

Since we do not always have the luxury of working on a new green field project with TDD, it is also possible to work on regression testing by generating tests for modules with something like this which I look forward to playing around with!