Created
September 10, 2021 17:21
-
-
Save ewascent/dbeb6755072f7d3e4aa06e7003b4510b to your computer and use it in GitHub Desktop.
Example of basic unit test in Golang
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
// running tests | |
// go tool test2json -t /tmp/w4vqgd_p/T/GoLand/___go_test_temp_testing_go.test -test.v -test.paniconexit0 | |
// example results | |
// === RUN TestAddition | |
// --- PASS: TestAddition (0.00s) | |
// === RUN TestBadMath | |
// --- PASS: TestBadMath (0.00s) | |
// === RUN TestSubtraction | |
// --- PASS: TestSubtraction (0.00s) | |
// PASS | |
//in main.go | |
package main | |
import "errors" | |
func mather(a int, b int, o string) (int, error){ | |
var x int | |
var err error | |
if o == "add"{ | |
x = a + b | |
} else if o == "subtract"{ | |
x = a - b | |
} else { | |
err = errors.New("Input " + o + " is an unsupported operation") | |
} | |
return x, err | |
} | |
//in main_test.go | |
package main | |
import ( | |
"testing" | |
) | |
func TestAddition(t *testing.T){ | |
expected := 4 | |
actual, err := mather(2,2, "add") | |
if expected != actual{ | |
t.Errorf("We expected %v and got %v", expected, actual) | |
} | |
if err != nil{ | |
t.Errorf("We got an error %v", err) | |
} | |
} | |
func TestBadMath(t *testing.T) { | |
expected := "Input divide is an unsupported operation" | |
actual, err := mather(100 , 2, "divide") | |
if actual != 0{ | |
t.Errorf("This should have been 0, the nil of int returns %v", actual) | |
} | |
if err.Error() != expected{ | |
t.Errorf("We got an unexpected error %v is not %v", err.Error(), expected) | |
} | |
} | |
func TestSubtraction(t *testing.T) { | |
expected := 98 | |
actual,err := mather(100 , 2, "subtract") | |
if expected != actual{ | |
t.Errorf("We expected %v and got %v", expected, actual) | |
} | |
if err != nil{ | |
t.Errorf("We got an error %v", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment