Skip to content

Latest commit

 

History

History
112 lines (85 loc) · 3.1 KB

testify.md

File metadata and controls

112 lines (85 loc) · 3.1 KB

testify

testify是一个第三方开发的测试工具包,支持如下特性:

断言(Easy assertions)

  • github.com/stretchr/testify/assert 提供了众多的断言函数,帮助我们判断结果是否符合我们预期,如:

    	assert := assert.New(t)
    	// assert equality
    	assert.Equal(123, 123, "they should be equal")
    
    	// assert inequality
    	assert.NotEqual(123, 456, "they should not be equal")
    
    	object := &Object{Value:"Something"}
    	// assert for nil (good for errors)
    	assert.Nil(object)
    	
    	// assert for not nil (good when you expect something)
    	if assert.NotNil(object) {
    		// now we know that object isn't nil, we are safe to make
    		// further assertions without causing any errors
    		assert.Equal("Something", object.Value)
    	}

    注: assert出错不会中断测试。

  • testify/require

    require包实现了assert包的函数,但是出错的时候不是返回bool类型的数值,而是调用t.FailNow()。

Mocking

创建接口

type Stringer interface {
	String() string
}

自动生成mock程序

mockery -name=Stringer 

// Stringer is an autogenerated mock type for the Stringer type
type Stringer struct {
	mock.Mock
}

// String provides a mock function with given fields:
func (_m *Stringer) String() string {
	ret := _m.Called()

	var r0 string
	if rf, ok := ret.Get(0).(func() string); ok {
		r0 = rf()
	} else {
		r0 = ret.Get(0).(string)
	}

	return r0
}

Testing suite interfaces and functions

​ 使用testify/suite 我们可以基于struct构建测试的初始化环境,并且在测试完成之后恢复环境,通过SetupTest和TearDownSuite接口。

type ExampleTestSuite struct {
	suite.Suite
	VariableThatShouldStartAtFive int
}

// 准备测试环境
func (suite *ExampleTestSuite) SetupTest() {
	log.Println("SetupTest")
	suite.VariableThatShouldStartAtFive = 5
}
// 恢复测试环境
func (suite *ExampleTestSuite) TearDownTest() {
	log.Println("TearDownTest")
}
// 测试案例
func (suite *ExampleTestSuite) TestExample() {
	assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
	suite.Equal(5, suite.VariableThatShouldStartAtFive)
}
// 执行ExampleTestSuite结构体里面的全部测试函数
func TestExampleTestSuite(t *testing.T) {
	// 运行ExampleTestSuite中Test开始的函数
	suite.Run(t, new(ExampleTestSuite))
}

参考资料