Announcing New Gomega Matchers
Gomega is a Golang library for writing lovely matcher/assertion statements in your unit tests. For example:
This rich syntax also allows Gomega to display an informative error message when a test fails.
While Gomega has provided a wealth of primitive matchers such as
HaveLen(...), it could use a little more power – a way to compose matchers into larger expressions.
After a little elbow grease, I’m happy to announce four new matchers are now available in the Gomega library:
Together, they provide a powerful way to compose existing matchers together into complex expressions.
Let’s take a brief look at the new matchers:
And, also named
SatisfyAll, returns true only if all of the provided matchers return true.
Or, also named
SatisfyAny, returns true only if at least one of the provided matchers return true.
Not negates the provided matcher, returning true only if the matcher returns false.
WithTransform lets you transform the value in some way before passing it to the given matcher.
But we could also create a lightweight matcher – a simple function that composes existing matchers. That is a powerful use case enabled by
WithTransform and the other new matchers. So the above example would become:
For more information refer to the Composing Matchers section of the Gomega documentation.
I leave you with one slightly ridiculous example, but it demonstrates what’s possible if necessary.
Imagine you want to verify that a
fetchPerson() function eventually returns one of multiple acceptable Person values.
When we compare two Person structs, we want to only consider certain fields. We don’t care about the
FetchedAt timestamp because that is somewhat random/unpredictable. So let’s create some lightweight field matchers:
We are now empowered to write complicated statements, such as this contrived example:
Hopefully you never have to write such convoluted tests, but it’s nice to know you could go there if you needed to.
Have fun testing your code with Gomega!