| Ask Me Anything | Build | GitHub | Mastodon | SourceHut

If you familiar with Go language, you knew that Go does not have an assert function or library. Here is six line of code that you can use in your code to check if data is equal or not when testing.

import (

func assert(t *testing.T, exp, got interface{}, equal bool) {
	if reflect.DeepEqual(exp, got) != equal {
		t.Fatalf("Expecting '%v' got '%v'\n", exp, got)

Let see what the assert function do.

The first parameter is pointer to testing object. The second parameter is your test expectation. The third parameter is a data returned from testing function. The fourth parameter is boolean, if its true thats mean you want your expectation equal with test data, otherwise you want your expectation do not match with data.

The recommended way to use this code is by adding it to your main package test. For example, if your package name is "tekstus" you should add it on file named "tekstus_test.go", and the rest of "*_test.go" files will automatically use it.

Here is some example on how to use it.

func Test... (t *testing.T) {
	input := []int{...}
	exp := []int{...}

	got := callFunctionToTest(input)

	assert(t, exp, got, true)

Happy testing :)