导航

golang单元测试

Posted on 2025-06-21 11:12  Zyeah  阅读(3)  评论(0)    收藏  举报

一、单元测试作用

个人理解,就是对单个文件进行测试,局部逻辑验证,不用每次整个项目测试。
待测文件:example.go

//example.go
func Add(){
  ...
}
func InsertMysql(where interface{},interface{}) bool{
}

测试文件命名:example_test.go

//example_test.go
funcTestAdd(t *testing.T){
//给出add函数入参
}
# 二、mock
如果涉及数据库的话,可以用
`gomock.MockGlobalFunc`去mock相关的全局函数
```go
g:= gomock.MockGlobalFunc(example. InsertMysql,func(where interface{},interface{})bool {return false })
defer g.Unpatch()