Basics | Testing
TDD Discipline#
- Write a test
- Make the compiler pass
- Run the test, see that it fails and check the error message is meaningful
- Write enough code to make the test pass
- Refactor
iterative, test-driven approach#
We make sure we take the smallest steps we can to have useful software. It's an important skill to be able to slice up requirements as small as you can so you can have working software.
Examples#
Go examples are executed just like tests so you can be confident examples reflect what the code actually does.
** Please note that the example function will not be executed if you remove the comment //Output: 6. Although the function will be compiled, it won't be executed.
By adding this code the example will appear in the documentation inside godoc, making your code even more accessible.
To try this out, run godoc -http=:6060 and navigate to http://localhost:6060/pkg/
Benchmarking#
The testing.B gives you access to the cryptically named b.N.
When the benchmark code is executed, it runs b.N times and measures how long it takes.
The amount of times the code is run shouldn't matter to you, the framework will determine what is a "good" value for that to let you have some decent results.
To run the benchmarks do go test -bench=. (or if you're in Windows Powershell go test -bench=".")
What 136 ns/op means is our function takes on average 136 nanoseconds to run (on my computer). Which is pretty ok! To test this it ran it 10000000 times.
NOTE by default Benchmarks are run sequentially.
Coverage#
go test -cover
Table driven tests#
Table driven tests are useful when you want to build a list of test cases that can be tested in the same manner.
And you can run specific tests within your table with go test -run TestArea/Rectangle.
quick#
quick.Check is a function that it will run against a number of random inputs, if the function returns false it will be seen as failing the check.