create Golang project with unitTest

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值