Go测试方法

Go测试方法

测试模板

拿取出个位数字例子

  1. 写数据源numbers
  2. 写want
  3. 写got
  4. want 和 got作比较

代码

// func: FetchUnitsDigit() (int, error)
// aim: 取出个位数字

func FetchUnitsDigit(data interface{}) (int, error) {
	toInt64, err := shift.ToInt64(data)
	if err != nil {
		return 0, err
	}

	res := toInt64 % 10
	return int(res), nil
}

测试代码

func TestFetchUnitsDigit(t *testing.T) {
	numbers := 3457.1189

	digit, err := FetchUnitsDigit(numbers)
	if err != nil {
		t.Fatal(err)
	}

	want := 7
	got := digit

	if want != got {
		t.Errorf("got %d want %d given, %v", got, want, numbers)
	}
}

同一个函数相同测试,数据源不同

func TestFetchUnitsDigit(t *testing.T) {
	t.Run("测试1", func(t *testing.T) {
		numbers := 3457.1189

		digit, err := FetchUnitsDigit(numbers)
		if err != nil {
			t.Fatal(err)
		}

		want := 7
		got := digit

		if want != got {
			t.Errorf("got %d want %d given, %v", got, want, numbers)
		}
	})

	t.Run("测试2", func(t *testing.T) {
		numbers := 33.123

		digit, err := FetchUnitsDigit(numbers)
		if err != nil {
			t.Fatal(err)
		}

		want := 7
		got := digit

		if want != got {
			t.Errorf("got %d want %d given, %v", got, want, numbers)
		}
	})

	t.Run("测试3", func(t *testing.T) {
		numbers := 892

		digit, err := FetchUnitsDigit(numbers)
		if err != nil {
			t.Fatal(err)
		}

		want := 7
		got := digit

		if want != got {
			t.Errorf("got %d want %d given, %v", got, want, numbers)
		}
	})
}

压力测试

func BenchmarkFetchUnitsDigit(b *testing.B) {
	for i := 0; i < b.N; i++ {
		FetchUnitsDigit(4.4441)
	}
}

http测试

文章: https://www.cnblogs.com/Detector/p/9769840.html

posted @ 2021-07-21 14:13  maob  阅读(168)  评论(0编辑  收藏  举报