前言
- 当我们完成一个模块后,先不着急继续完成其他模块,而是进行单元测试,这样我们能够提前发现当前模块的错误,减少整个项目完成后出现的bug。
- 可以了解下TDD(测试驱动开发)
1.需要的包
1.常用的包
import (
"github.com/agiledragon/gomonkey"
"github.com/stretchr/testify/assert"
)
2.补充包
import (
"github.com/alicebob/miniredis/v2"
"github.com/DATA-DOG/go-sqlmock"
)
2.外部调用模块
1.person.go
package unittesting
func Eat(s string,t bool) bool {
return true
}
2.user.go
package unittesting
func Add() bool {
result := Eat("eat",true)
return result
}
3.单元测试
package unittesting
import (
"github.com/agiledragon/gomonkey"
"github.com/stretchr/testify/assert"
"testing"
)
func TestUser(t *testing.T) {
t.Run("测试:外部func调用失败",t, func(t *testing.T) {
gomonkey.ApplyFunc := gomonkey.ApplyFunc(Eat, func(_ string, _ bool) bool {
return false
})
defer applyFunc.Reset()
actual := Add()
assert.Equal(t,false,actual)
})
}
3.外部方法模块 (为一个方法打桩)
1. person.go (method)
package unittesting
type Person struct {
name string
}
func (p *Person) Play(s string,t bool) error {
return nil
}
2.user.go
package unittesting
func Add() error {
person := Person{
name: "Tom",
}
err := person.Play("", false)
return err
}
3.user_test.go
package unittesting
import (
"errors"
"github.com/agiledragon/gomonkey"
"github.com/stretchr/testify/assert"
"reflect"
"testing"
)
func TestUser(t *testing.T) {
t.Run("测试:外部method调用err",t, func(t *testing.T) {
var p *Person
gomonkey.ApplyMethod := gomonkey.ApplyMethod(reflect.TypeOf(p), "Play", func(_ *Person, _ string, _ bool) error {
return errors.New("test Err")
})
defer applyMethod.Reset()
actualErr := Add()
assert.Equal(t,"test Err",actualErr.Error())
})
}