1, create new project “test4_unittest”
$ cd ~/project
$ mkdir test4_unittest
2, create new module for project “test4_unittest”
$ cd test4_unittest
$ mkdir pkg
3, initialize “pkg” folder
$ cd pkg
$ touch lib.go
$ touch lib_test.go
4,add following lines in “lib.go”
package pkg
import (
"math"
"errors"
)
func Asin(a, b float64) (float64, error) {
if (b == 0.0) {
return 0.0, errors.New("Invalid value")
}
return math.Asin(a / b), nil
}
func Acos(a, b float64) (float64, error) {
if (b == 0.0) {
return 0.0, errors.New("Invalid value")
}
return math.Acos(a / b), nil
}
func Atan(a, b float64) float64 {
var r float64
if (b == 0.0) {
if (a > 0.0) {
r = math.Pi / 2.0
} else if (a == 0.0) {
r = 0.0
} else {
r = math.Pi / -2.0
}
} else {
r = math.Atan(a / b)
}
return r
}
func Acot(a, b float64) float64 {
return Atan(b, a)
}
5, add following lines in “lib_test.go”
package pkg
import (
"fmt"
"testing"
)
func TestAsin(t *testing.T) {
var a, b float64
a = 1.0
b = 0.0
r, err := Asin(a, b)
if (err != nil) {
t.Fatalf("Failed in TestAsin: %v, %v", a, b)
}
fmt.Println("Result of Asin: ", r)
}
func TestAcos(t *testing.T) {
var a, b float64
a = 1.0
b = 0.0
r, err := Acos(a, b)
if (err != nil) {
t.Fatalf("Failed in TestAcos: %v, %v", a, b)
}
fmt.Println("Result of Acos: ", r)
}
func TestAtan(t *testing.T) {
r := Atan(1.0, 0.0)
fmt.Println("Result of Atan: ", r)
}
func TestAcot(t *testing.T) {
r := Acot(-1.0, 0.0)
fmt.Println("Result of Acot: ", r)
}
6, run unit test
$ go test -v
you should get test result like this:
=== RUN TestAsin
lib_test.go:14: Failed in TestAsin: 1, 0
--- FAIL: TestAsin (0.00s)
=== RUN TestAcos
lib_test.go:25: Failed in TestAcos: 1, 0
--- FAIL: TestAcos (0.00s)
=== RUN TestAtan
Result of Atan: 1.5707963267948966
--- PASS: TestAtan (0.00s)
=== RUN TestAcot
Result of Acot: -0
--- PASS: TestAcot (0.00s)
FAIL
exit status 1
FAIL pkg 0.002s