编程初学者的Go语言学习之旅 | 青训营笔记

84 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第3天。

Go语言工程实践之测试

测试通常是避免事故的最后一道屏障。

回归测试

质量保证人员通过手动终端回归固定的主流场景。

集中测试

对系统、功能维度做测试验证,对服务暴露的某些接口做自动化的回归测试。

单元测试

面对测试开发阶段,对单独的函数模块做测试验证。单元测试的覆盖率在一定程度上决定着代码的质量。

三者从上至下覆盖率逐渐提升,成本逐渐降低。

单元测试

输入->测试单元->输出 然后和期望的输出校对,即可完成一次测试。 测试单元:接口、函数模块等。

那么在代码层面上,Go如何进行单元测试?

单元测试规则

1.所有测试文件以_test.go 结尾 2.函数命名规范:func TestXxx(*testing.T) 3.提供了一个func TestMain(m *testing.N)函数,用来进行数据装载、配置初始化等前置工作,并可以用来进行释放资源等收尾工作。 code := m.Run()运行单元测试。

下面我们做一个简单的示范:

//main.go中
package Example  
  
func Hello() string {  
   return "halo"  
}
//main_test.go中
package Example  
  
import "testing"  
  
func TestHello(t *testing.T) {  
   Output := Hello()  
   ExpectOutput := "hallo"  
   if Output != ExpectOutput {  
      t.Errorf("Something wrong happened in your func,because %s is not match %s", Output, ExpectOutput)  
   }  
}

输出为:

=== RUN   TestHello
    main_test.go:9: Something wrong happened in your func,because halo is not match hallo
--- FAIL: TestHello (0.00s)

FAIL

这样就成功完成了一次单元测试。

单元测试-覆盖率

代码覆盖率可以衡量代码是否经过了足够的测试。越完备保证代码的正确率。下面举一个例子:

//main.go中
package Example  
  
func Exam(score int) bool {  
   if score > 60 {  
      return true  
   } else {  
      return false  
   }  
}
//main_test.go中
package Example  
  
import "testing"  
  
func TestExamRight(t *testing.T) {  
   Output := Exam(70)  
   if Output == true {  
      t.Errorf("pass")  
   }  
}

输出结果(使用-cover参数运行):

=== RUN   TestHelloRight
    main_test.go:8: pass
--- FAIL: TestHelloRight (0.00s)

FAIL

coverage: 66.7% of statements in ./...

这里的覆盖率是66.7%,怎么算出来的? 实际上,此处的test只测试了Exam函数的前两行,也就是score>60,返回true的情况,如果我们需要覆盖率达到100%,我们需要修改main_test.go,添加一个测试函数:

//main_test.go中
package Example  
  
import "testing"  
  
func TestExamRight(t *testing.T) {  
   Output := Exam(70)  
   if Output == true {  
      t.Errorf("pass")  
   }  
}  
  
func TestHelloWrong(t *testing.T) {  
   Output := Exam(50)  
   if Output == false {  
      t.Errorf("fail")  
   }  
}

输出:

=== RUN   TestExamRight
    main_test.go:8: pass
--- FAIL: TestExamRight (0.00s)

=== RUN   TestHelloWrong
    main_test.go:15: fail
--- FAIL: TestHelloWrong (0.00s)

FAIL

coverage: 100.0% of statements in ./...

可以看到覆盖率达到了100%,测试完了整个Exam函数。 在开发中,一般测试率在50%-80%之间,虽然是越高越好,但100%往往是一个理想化的目标。