Golang: Writing test cases in Go

In this article, we’re going to look at how we write test cases in Golang. Here, I will create a file called acct_test.go; which can be run by simply typing go test into the terminal.

The first function tests the creation of a new account. Inside this, we make check the length of the new account slice that is created. We expect it to return a length of 12; if it doesn’t an error is passed to the test handler.

Next, we check the values in the slice. If the first value of the slice doesn’t equal ‘BankName’ it’ll pass an error to the test handler & if the final value isn’t ‘Savings’, it will again throw an error.

Now, we are going to test the save file function. This test:

  1. Removes a test file (if there is one)
  2. Creates a new account by calling the new account function
  3. Saves that account to a file
  4. Reads that file
  5. Runs a length check
  6. Removes the test file

This little test would be enough to prove a file was created & the contents were of the correct length.