• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / Getting Started With Golang Unit Testing

Getting Started With Golang Unit Testing

December 23, 2015 by Rana Ahsan 1 Comment

golang unit testing

It’s been a long since I wrote my last blog post. I am feeling really happy to be able to make a comeback again. Hope I can hold this from now on. So, in these last couple of months, I have learned a lot and one of them is to get into Golang. I loved this language and its capability. As part, I had to dive into Golang unit testing as well. However, interestingly, I did find very few resources that are useful for me as a beginner in this area.

One of the interesting readings was this medium post which showed some interesting approaches to writing tests. If you have a few extra minutes, go ahead and read on!

After starting with a different approach, we were able to become stable in one approach, which I am gonna explain today. Obviously, this is a beginner’s tutorial with the aim that you have a quick start without wasting much time or heads around.

Golang Unit Testing Resources:

  • Native Support: Well, you will be happy to know that, Golang itself has very nice support for testing. So, you can write your tests even without any third-party tools at all.
  • Testify Assertion Library: Though providing very useful and powerful native support, unfortunately, Golang doesn’t provide any behavioural/assertion library. If you were about to start writing tests in Golang and haven’t found this awesome assertion library, testify yet, you were gonna miss a lot! Besides providing assertion support, it also comes up with a test suite library, which will be very useful for you to write tests with setup/teardown methods. This is the main library which I used for this tutorial.

Writing Tests:

Golang conventions:

  • Write tests in the same directory as the source files are in.
  • name the test files as “{source_filename}_test.go” structure
  • You can name separate packages for test files. But it is only recommended if you are writing tests for exported interfaces only. To write tests for both exported/internals, you should use the same package name.
  • For test methods, they should follow pascal’s case structure name like “TestMyFunc”. A name like “TestmyFunc” wouldn’t work and not be executed at all, as it expects the following letter after ‘Test’ to be a capital letter. If you are testing internal functions which start with small letters and you would like to use the same name in the test file as well, use conventions like “Test_myFunc”, which will work just fine.

Golang Test Suite Skeleton

Here is a basic skeleton of the test suite for you. Use the appropriate setup/tear-down as per your need. and the test suite struct is for adding necessary variables that you would like to set across setup/test methods/

type myTestSuite struct {
  suite.Suite
}

func (suite *myTestSuite) SetupSuite() {
}

func (suite *myTestSuite) TearDownSuite() {
}

func (suite *myTestSuite) SetupTest() {
}

func (suite *myTestSuite) TearDownTest() {
}

func (suite *myTestSuite) TestMyFunc() {
}

func TestMyTestSuite(t *testing.T) {
  tests := new(myTestSuite)
  suite.Run(t, tests)
}Code language: JavaScript (javascript)

You will notice that we are writing all our test functions as part of the struct, which will be automatically called via testify library. Usually, Golang passes and instance of the test. So, we are taking that in our above ‘TestMyTestSuite’ method and passing that to the testify struct we just coded. It will internally call all the test methods we have created(in this example, ‘TestMyFunc’).

Example Test method

A sample of how a test function could be is as follows:

func (suite *myTestSuite) TestMyFunc() {
  assert.NotEqual(suite.T(), "foo", "bar", "oo and bar aren't equal")
  assert.Equal(suite.T(), "foo", "foo", "Should pass as equal")
  assert.Nil(suite.T(), nil, "expected nil value")
}
Code language: JavaScript (javascript)

If some conditions don’t look good, fail them forcefully:

assert.Fail(suite.T(), "It's failing intentionally")
Code language: JavaScript (javascript)

Skipping a test:

Sometimes, either because of a deadline or you just not feeling some tests are that important, you will want to skip them for now, but come back and write them later on. If you want to skip writing some tests, but want to keep track of them, use the following line:

if testing.Short() {
    suite.T().Skip("Skipping this test for now")
}
Code language: JavaScript (javascript)

It will need an extra flag(‘-test.short’, which isn’t set by default) to show up in the output as skipped status, which you will find in the next section

Running Tests:

to run tests, Golang provides the generic ‘go test’ method. To make it more useful, you can use something like as follows:

go test -timeout 120s -v -short

If you have multiple packages that you would like to run tests together for, use a command like this:

go test ./... -timeout 120s -v -short

Test Coverage:

It’s always best to see the test coverage to plan and write tests for the uncovered code segments. Golang also comes up with a very nice support for coverage as well. You will need to use two extra flags to tell the Go compiler to analyze test coverage and pass a file path name in which it will save the coverage report.

go test -timeout 120s -v -short -cover -coverprofile=coverage.out

To see the coverage on a nice HTML view, use this command after running the above command:

go tool cover -html=coverage.out
golang code coverage

It will have the list of all files in the package you just ran tests for and coverage details.

Final Words:

This is just a basic overview of how to get started with Golang unit testing, which might be in your help to have a kick-ass start as a beginner! If any basic parts are missing that you would like to know, feel free to comment and I will update the post with more details. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: golang, unit-test

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. djui says

    December 24, 2015 at 7:25 am

    I would suggest having a look at the `require.` package next to the `assert.` package in Testify. The difference is `assert.` uses `Fail()` but `require.` uses `FailNow()`. Not all tests can be written in a way allowing to continue after a failure. One example is: Imagine you instantiate an object, but that fails Continuing then, even though one used `Assert.NoError()` will only make the test as failed, but not stop it, leading to not very pretty panics in your test output.

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023