Created
July 23, 2013 02:50
-
-
Save samalba/6059502 to your computer and use it in GitHub Desktop.
How to assert values in golang unit tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
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
This function can be simplified to:
You don't need the return and the testing module provides a
Fatalf
function to format messages