That's when instead of comparing the expected and actual values in code:
assert.Equal(t, expected, actual)
You instead assert that the actual value is equal to a known canonical value stored in a file canonical.json
:
canonical.Assert(t, actual)
This approach is especially useful when comparing large values.
First, download the library with go get github.com/bennydictor/canonical
.
At the top of your test file, add the line
//go:generate go test . -ldflags "-X 'github.com/bennydictor/canonical.Canonize=true'"
Run go generate ./your/package/with/tests
. This will generate the canonical.json
file.
Look at it and see if the values there make sense, and if not, fix your code.
Add canonical.json
to your version control system.
Assert
and Require
will now compare asserted values with the canonical values saved in canonical.json
.
Also, there's an example.
There must be at most one call to Assert
or Require
per test. Assert multiple values like this:
canonical.Assert(t, foo, bar, baz)
Or like this:
canonical.Assert(t, map[string]interface{}{
"foo": foo,
"bar": bar,
"baz": baz,
})
As you may have noticed, the values are converted to json in order to be stored and compared. If your value has private fields anywhere in it, those private fields will not be included in the json. That's just how Go works, I can't do anything about it.
Try changing the fields to be public. If that's impossible or you don't want to,
then you'll have to assert them one by one (e.g. canonical.Assert(t, result.foo, result.bar)
).
I made a wrapper for errors tho: canonical.Assert(canonical.Error(err))
(works with nil
errors).
Look at the test diff. If you agree with it, then run go generate ./your/package/with/tests
.
If you don't agree with the diff, fix your code.
Get the version you want from your version control system. If you don't use a version control system, sorry, I can't help you.