go test使用

84 阅读1分钟

背景

golang的测试工具 go test非常好用,特此做个总结和模板化

example

假设我新建一个文件code2582.go包含函数xxx

package code2582

// passThePillow 2852题 递枕头
/*
   思路:判断time对2(n-1)取模为t,随之判断t是大于n-1还是小于,获取最后值
*/
func passThePillow(n int, time int) int {
   t := time % (2 * (n - 1))
   var result int
   if t <= (n - 1) {
      result = 1 + t
   } else {
      result = n - (t - (n - 1))
   }
   return result
}

此时要测试这个函数是否有效,则新建一个文件code2582_test.go包含测试函数Testxxx

package code2582

import "testing"

func TestPassThePillow(t *testing.T) {
   type args struct {
      n    int
      time int
   }
   tests := []struct {
      name string
      args args
      want int
   }{
      {
         name: "test1",
         args: args{4, 5},
         want: 2,
      },
      {
         name: "test2",
         args: args{3, 2},
         want: 3,
      },
   }
   for _, tt := range tests {
      t.Run(tt.name, func(t *testing.T) {
         if got := passThePillow(tt.args.n, tt.args.time); got != tt.want {
            t.Errorf("passThePillow() = %v, want %v", got, tt.want)
         }
      })
   }
}

说明

这个tests结构来自于goland,配合goland一起使用效果更佳。但也可以通过命令

go test -run TestPassThePillow