Skip to content

Instantly share code, notes, and snippets.

@samalba
Created July 23, 2013 02:50
Show Gist options
  • Save samalba/6059502 to your computer and use it in GitHub Desktop.
Save samalba/6059502 to your computer and use it in GitHub Desktop.
How to assert values in golang unit tests
package main
import (
"fmt"
"testing"
)
func assertEqual(t *testing.T, a interface{}, b interface{}, message string) {
if a == b {
return
}
if len(message) == 0 {
message = fmt.Sprintf("%v != %v", a, b)
}
t.Fatal(message)
}
func TestSimple(t *testing.T) {
a := 42
assertEqual(t, a, 42, "")
assertEqual(t, a, 43, "This message is displayed in place of the default one")
}
@devak23
Copy link

devak23 commented Jul 15, 2017

Thank you! Unittesting now became a tad bit easier 👍

@danidee10
Copy link

danidee10 commented Jan 25, 2018

This function can be simplified to:

package main

import "testing"

func assertEqual(t *testing.T, a interface{}, b interface{}) {
	if a != b {
		t.Fatalf("%s != %s", a, b)
	}
}

You don't need the return and the testing module provides a Fatalf function to format messages

@gabemeola
Copy link

gabemeola commented Sep 18, 2018

Additional type info

package main

import (
	"reflect"
	"testing"
)

// AssertEqual checks if values are equal
func AssertEqual(t *testing.T, a interface{}, b interface{}) {
	if a == b {
		return
	}
	// debug.PrintStack()
	t.Errorf("Received %v (type %v), expected %v (type %v)", a, reflect.TypeOf(a), b, reflect.TypeOf(b))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment