Not sure how to structure your Go web application?
My new book guides you through the start-to-finish build of a real world web application in Go — covering topics like how to structure your code, manage dependencies, create dynamic database-driven pages, and how to authenticate and authorize users securely.
Quick tip: Easy test assertions with Go generics
Published on:
Now that Go 1.18 has been released with support for generics, it's easier than ever to create helper functions for your test assertions.
Using helpers for your test assertions can help to:
Make your test functions clean and clear;
Keep test failure messages consistent;
And reduce the potential for errors in your code due to typos.
To illustrate this, let's say that you have a simple greet() function that you want to test:
In the past, your test for the greet() function would probably look something like this:
With Go 1.18, we can use generics and the comparable constraint to create an Equal() helper function which carries out our test assertions. Personally, I like to put this in a reusable assert package.
Like so:
And with that in place, the TestGreet() test can be simplified like so:
If you enjoyed this article, you might like to check out my recommended tutorials list or check out my books Let's Go and Let's Go Further, which teach you everything you need to know about how to build professional production-ready web applications and APIs with Go.