on
Writing Tests in Go (a Beginners Guide)
There a many benefits to testing your code in general, which we won’t go into detail on (but if you’re interested, take a look here) all we will say is the quote below.
“Imperfect tests, run frequently, are much better than perfect tests that are never written at all”. - Fowler
First Test
We’ve created the most basic progam, to add two numbers together, below in main.go
which we’re going to write a test for. Tests in Go are found in separate files to the code and are within *_test.go
- where * is the filename. So our test would be main_test.go
- but if your go file was address.go
, you’d create a address_test.go
and store them here.
main.go
|
|
main_test.go
|
|
You can see in our test above, we have imported the testing
package which allows us to a) define a test and b) mark tests as failed.
This is great, but how do I run them?
Run in the command line:
|
|
Should output something like:
|
|
If you want to find out how to run all tests for your project, or running them in more detail.
How to: Run all Tests