单元测试

go test指令

  • go test, 运行测试
  • go test -v -short -cover -parallel 3
    • -v verbose
    • -short 忽略时间过长的测试
    • -cover 覆盖率
    • -parallel 3,同时运行3个测试用例,不过需要在测试中写t.parallel()来告诉go test
  • go test -bench . -run x,运行当前目录的所有基准测试,并运行x的功能测试,因为没有x匹配,所以相当于忽略所有功能测试

测试http

testing/httptest,模拟web服务器所需的设施,用net/http中的客户端去请求,然后模拟服务器返回的响应。

test double 测试替身

提高被测试代码的独立性。

实现测试替身的一种设计方法是使用依赖注入模式,dependency injection。

Go中被传入的依赖关系通常会是一种接口类型。

三方

  • Gocheck
  • Ginkgo