Testing in Go by example: Part 4Our approach to assertions in Go code
Michael Whatcott
Michael Whatcott
 • 
August 11, 2015
Tags

I think it's time for a slight detour. In part 1 we covered the basics of testing in go. In part 2 we covered a few slick ways to execute tests. In part 3 we covered some of our recent endeavors at Smarty to build on the basics. Toward the end of that post we went into some detail regarding our approach to assertions. The assertions referenced in the GoConvey project are actually their own separate project that are imported into GoConvey. The nice thing about separating the assertions into their own separate project is that they can be used, well, separately. In this post I'll show you some of the the different ways we use the assertions project in our code outside of the GoConvey project.

In GoConvey, the So function exported by the convey package is void. All results of calling So() are swallowed by the convey functionality and passed to the reporting mechanisms. The assertions package (in the assertions project) exports its own version of the So() function, but it returns 2 parameters:

func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string)

Here's the GoDoc comment:

So is a convenience function (as opposed to an inconvenience function?) for running assertions on arbitrary arguments in any context, be it for testing or even application logging. It allows you to perform assertion-like behavior (and get nicely formatted messages detailing discrepancies) but without the program blowing up or panicking. All that is required is to import this package and call So with one of the assertions exported by this package as the second parameter. The first return parameter is a boolean indicating if the assertion was true. The second return parameter is the well-formatted message showing why an assertion was incorrect, or blank if the assertion was correct.

You probably noticed the unexported type assertion in the So() signature above. Here's what it looks like:

// assertion is an alias for a function with a signature that the So()
// function can handle. Any future or custom assertions should conform to this
// method signature. The return value should be an empty string if the assertion
// passes and a well-formed failure message if not.
type assertion func(actual interface{}, expected ...interface{}) string

Each of the Should assertion functions in the assertions package can be used as an assertion func when calling So().

Here's a simple example of how to use So() with an assertion function in your code:

x, y := 99, 100
if ok, message := So(x, ShouldBeGreaterThan, y); !ok {
    log.Println(message)
    // or log.Fatal(message) if you're feeling unforgiving...
}

Notice that this example makes no reference to the "testing" package's *testing.T, but it could:

x, y := 99, 100
if ok, message := So(x, ShouldBeGreaterThan, y); !ok {
    t.Error(message)
}

If you know you're going to be using So within your test functions and calling t.Error() and the like, here's another way to use the assertions package:

func TestSomething(t *testing.T) {
	x, y := 99, 100
	assertions.New(t).So(x, ShouldBeGreaterThan, y)
}

Did you notice how we passed in t in the assertions.New() function? The nice thing about this approach is you don't actually have to call t.Error() in failure scenarios. That is handled by the Assertion.So() function because it is given a reference to t.

You can actually call .So() multiple times on an Assertion instance:

assert := assertions.New(t)
assert.So(1, ShouldBeGreaterThan, 2)
assert.So(true, ShouldBeFalse)
assert.So(time.Now(), ShouldHappenBefore, time.Now())
// etc...

You can find out if any of those assertions failed and act accordingly:

if assert.Failed() {
	log.Fatal("Ouch")
}

You've probably noticed that to be able to reference assertions.New and ShouldEqual you'll need an import statement like this:

import (
	"github.com/smartystreets/assertions"
	. "github.com/smartystreets/assertions"
)

func TestSomething(t *testing.T) {
	assert := assertions.New(t)
	assert.So(1, ShouldBeGreaterThan, 2)
	assert.So(true, ShouldBeFalse)
	assert.So(time.Now(), ShouldHappenBefore, time.Now())
}

That's somewhat awkward so we created an alias package for the assertion functions called should:

import (
	"github.com/smartystreets/assertions"
	"github.com/smartystreets/assertions/should"
)

func TestSomething(t *testing.T) {
	assert := assertions.New(t)
	assert.So(1, should.BeGreaterThan, 2)
	assert.So(true, should.BeFalse)
	assert.So(time.Now(), should.HappenBefore, time.Now())
}

Did you catch the difference? ShouldBeGreaterThan becomes should.BeGreaterThan. If you're using goimports then this approach works out really smoothly. If you're not using goimports, why not? It's easy to setup.

The moral of the story is that it should be easy to check that a value is what you expect it to be. We prefer not to write if statements and hand-crafted log statements whenever possible so we've created the assertions package that helps us in various contexts, both in testing and otherwise. In the next post we'll talk about yet another use of the assertions package as we talk about our newest test library called gunit.

Before signing off, I would be remiss if I didn't give credit to Aaron Jacobs, the creator of the oglematchers package, which many of the assertion functions use internally to do their jobs.

Subscribe to our blog!
Learn more about RSS feeds here.
rss feed iconSubscribe Now
Read our recent posts
Navigating the Future: Geocoding & Address Data Trends in the Cloud
Arrow Icon
In a recent webinar, Berk Charlton, Chief Product Officer at Smarty, provided an in-depth look at our industry-leading address intelligence suite designed to provide highly accurate geocoding and address validation. Here are the main points Berk covered during the session:Comprehensive Product Suite: Smarty offers a wide range of products, including address validation, rooftop geocoding, global address auto-complete, and address data enrichment. These tools are designed to handle various aspects of address management and enhancement in industries from Insurance to Healthcare to Telecom and more.
Unlocking Ecommerce Success: Fabletics' Journey with Address Autocomplete
Arrow Icon
In the growing world of ecommerce, providing a seamless checkout experience is key for customer satisfaction and conversion rates. Fabletics, a leading activewear brand, embarked on a conversion-improving journey with Smarty to enhance their checkout process. We recently hosted a webinar filled with insights from Mel Cummings, Vice President of Product Management and UX at Fabletics. Unlocking Ecommerce SuccessConsider this common scenario: your customer is navigating through an online checkout process, only to be thwarted by an error, often related to address entry.
Avoid Awkward Moments with Smarty's Accurate Data
Arrow Icon
March 18 marks a bit of an awkward holiday: Awkward Moments Day. It's a day that celebrates those times that make you cringe, moments that make you face-palm, and stories that wake you up at 4 in the morning thinking, "Ugh! Why did I do that?" Although these moments can be uncomfortable, it's helpful to remember that everyone has them, and if they say they don't … We know they’re lying.  It's also helpful to remember that these embarrassing stories can help us learn and do better the next time around.
Ready to get started?