《用 Gin 框架构建分布式应用》学习第 15 天,p272-p306 总结,总 35 页。
一、技术总结
1.TDD(test-driven development)
虽然经常看到 TDD 这个属于,从本人的工作经历看,实际开发中用得相对较少。
2.unitest(单元测试)
go 语言开发中,使用 testify 进行单元测试开发。
(1)创建测试文件
测试文件以 xxx_test.go 命名,与 xxx.go 在同一目录下。示例:main.go 和 mian_test.go 在同一目录下。
(2)编写测试函数
测试函数必须 Test 作为前缀,后面跟被测试函数名,示例:被测试函数名称为 IndexHandler,测试函数名称为 TestIndexHandler。
main.go:
// main.gopackage main
import ( "github.com/gin-gonic/gin" "net/http")
func IndexHandler(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "hello world"})}
func SetupServer() *gin.Engine { router := gin.Default() router.GET("/", IndexHandler) return router}func main() { err := SetupServer().Run() if err != nil { return }}
复制代码
main_test.go:
package main
import ( "github.com/stretchr/testify/assert" "io" "net/http" "net/http/httptest" "testing")
func TestIndexHandler(t *testing.T) { // 不适用 testify // 注意,因为`{"message":"hello world"}`是字符串,所以冒号后面如果有空格,在判断相等的时候也会有影响 // mockUserResp := `{"message":"hello world"}` // // ts := httptest.NewServer(SetupServer()) // defer ts.Close() // // res, err := http.Get(ts.URL + "/") // if err != nil { // t.Fatalf("Expected no error: got %v", err) // } // // defer res.Body.Close() // // if res.StatusCode != http.StatusOK { // t.Fatalf("Expected status code 200: got %v", res.StatusCode) // } // // // ioutil.ReadAll 已不推荐使用 // // responseData, err := ioutil.ReadAll(res.Body) // responseData, err := io.ReadAll(res.Body) // if string(responseData) != mockUserResp { // t.Fatalf("Expected hello world message: got %v", string(responseData)) // }
// 使用 testify mockUserResp := `{"message": "hello world"}`
ts := httptest.NewServer(SetupServer()) defer ts.Close()
res, err := http.Get(ts.URL + "/") defer res.Body.Close()
assert.Nil(t, err) assert.Equal(t, http.StatusOK, res.StatusCode)
responseData, err := io.ReadAll(res.Body) assert.Equal(t, mockUserResp, string(responseData))}
复制代码
(3)执行测试
3.coverage(测试覆盖率)
p282, Test coverage describes how much of a package's code is exercised by running the package's tests.
4.integration test(集成测试)
integration test 就是多个功能一起测试。
5.security test(安全测试)
go 语言开发中,使用 gosec 进行安全测试。
6.postman
书上介绍了 postman 的 collection, environment, scripts 的使用,基本属于工作中常用到的操作。当然,postman 本身也不复杂。
go 语言开发中,使用
7.吐槽系列
// chapter 01
router := gin.Default()
// chapter 07
r := gin.Default()
复制代码
作者在 chapter 01 用的名称是 router, 那么在 chapter 07 也应该用这个,而不是 r,保持字段名称的一致性!想起本人在实际工作中遇到的一个项目,其中表示“设备”的名称就用了三个:eqp, equip, equipment,但其实都是指同一个东西,这无形中会导致一些问题:(1)阅读代码的人会有疑问,这三个表示的是同一个东西吗?(2)写代码的时候得思考,用的是哪个名称。
二、英语总结
无。
三、其它
今天没有什么想说的。
四、参考资料
1. 编程
(1) Mohamed Labouardy,《Building Distributed Applications in Gin》:https://book.douban.com/subject/35610349
2. 英语
(1) Etymology Dictionary:https://www.etymonline.com
(2) Cambridge Dictionary:https://dictionary.cambridge.org
欢迎搜索及关注:编程人(a_codists)
评论