Writing Unit Tests in Go — Basics

Unit tests are functions that are designed to test small units of functionality in your code.

To write a unit test in Go, you will need to:

  1. Declare a function with a name that starts with “Test” and has a single argument of type “testing.T”. This function will contain your test case.
  2. Within the test function, use the various methods provided by the “testing” package to perform checks on the behavior of your code. For example, you can use the “assert.Equal” or “assert.NotEqual” method to fail the test if a certain condition is not met.
  3. Run the test using the “go test” command.

Here is an example of a unit test in Go:

This test function will test the “sum” function in the “mypackage” package by calling it with the arguments 1 and 2 and checking that the result is 3. If the result is not 3, the test will fail with an error message.

--

--

Software Engineer. Writes about AWS, Python, Go, Self Help & more. https://zaidafzal.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store