测试框架testify使用

testify
https://github.com/stretchr/testify
● 断言
原生测试框架里面缺失断言功能,在很多场景下都不方便,testify 提供的断言功能开箱即用,与原生测试框架完美契合:
func TestAssert(t *testing.T) {
assert := assert.New(t)

assert.Equal(123, 123, “they should be equal”)

assert.NotEqual(123, 456, “they should not be equal”)

o := make(map[string]string)
o[“ray”] = “jun”

if assert.NotNil(o) {
assert.Equal(“jun”, o[“ray”])
} else {
assert.Nil(o)
}
}
● Mock 能力
testify 提供了 Mock 的能力,可以很好的模拟测试需要的数据,对于一些需要复杂数据的测试很有帮助:
type MyMockedObject struct{
mock.Mock
}

func (m *MyMockedObject) DoSomething(number int) (bool, error) {
args := m.Called(number)
return args.Bool(0), args.Error(1)

}

func TestSomething(t *testing.T) {
testObj := new(MyMockedObject)

testObj.On(“DoSomething”, 123).Return(true, nil)

testMockObj(testObj)

testObj.AssertExpectations(t)
}

func testMockObj(mcObj *MyMockedObject) {
fmt.Println(mcObj.DoSomething(123))
}
● 构建更完善的测试
即使有了 TestMain 来初始化配置,但也还是不够灵活,比如在一个包下,我需要包含多组测试,而且每组测试的初始化都不一样,而 testify 提供的 suite 包提供了更加面向对象的测试方式,并且也提供了 setup/teardown 等方法来初始化和回收资源,可以直接使用 go test 进行测试,不会对现有的测试框架有侵入性修改:
type ExampleTestSuite struct {
suite.Suite
VariableThatShouldStartAtFive int
}

func (suite *ExampleTestSuite) SetupTest() {
fmt.Println(“run setup method”)
suite.VariableThatShouldStartAtFive = 5
}

func (suite *ExampleTestSuite) TearDownTest() {
fmt.Println(“run tear down method”)
suite.VariableThatShouldStartAtFive = 0

}

func (suite *ExampleTestSuite) TestExample() {
assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
}

func TestExampleTestSuite(t *testing.T) {
suite.Run(t, new(ExampleTestSuite))
}

关注公众号:关大仙的学习笔记

后续高质量文章都会发布到这个公众号上

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值