Go语言测试库stretchr/testify

这篇具有很好参考价值的文章主要介绍了Go语言测试库stretchr/testify。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Go语言测试库stretchr/testify

在其他语言中处理测试时,你可能熟悉使用断言和期望。但是,在Go中,我找不到类似的东西,直到我发现了

testify包,Testify的 assert 包为我们的测试提供了各种有用的工具。

Github地址:https://github.com/stretchr/testify

官方文档:https://pkg.go.dev/github.com/stretchr/testify

1、安装

go get github.com/stretchr/testify

2、assert package

package go_testify

import (
	"github.com/stretchr/testify/assert"
	"testing"
)

type Object struct {
	Value string
}

func TestSomething(t *testing.T) {
	var object =  Object{Value: "Something"}
	// assert equality
	assert.Equal(t, 123, 123, "they should be equal")
	// assert inequality
	assert.NotEqual(t, 123, 456, "they should not be equal")
	// assert for nil (good for errors)
	assert.Nil(t, nil)
	// assert for not nil (good when you expect something)
	if assert.NotNil(t, object) {
		// now we know that object isn't nil, we are safe to make
		// further assertions without causing any errors
		assert.Equal(t, "Something", object.Value)
	}
}
$ go test -v 001_test.go
=== RUN   TestSomething
--- PASS: TestSomething (0.00s)
PASS
ok      command-line-arguments  0.290s

如果多次断言,请使用以下命令:

package go_testify

import (
	"github.com/stretchr/testify/assert"
	"testing"
)

type Object struct {
	Value string
}

func TestSomething(t *testing.T) {
	var object = Object{Value: "Something"}
	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")
	// assert for nil (good for errors)
	assert.Nil(nil)
	// 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)
	}
}
$ go test -v 002_test.go
=== RUN   TestSomething
--- PASS: TestSomething (0.00s)
PASS
ok      command-line-arguments  0.033s

3、require package

require包提供了与assert包相同的全局函数,但它们并没有返回布尔结果,而是终止了当前测试。

package go_testify

import (
	"github.com/stretchr/testify/require"
	"testing"
)

type Object struct {
	Value string
}

func TestSomething(t *testing.T) {
	var object = Object{Value: "Something"}
	require.Equal(t, 123, 123, "they should be equal")
	require.NotEqual(t, 123, 456, "they should not be equal")
	require.Nil(t, nil)
	require.NotNil(t, object)
}
$ go test -v 003_test.go
=== RUN   TestSomething
--- PASS: TestSomething (0.00s)
PASS
ok      command-line-arguments  0.261s
package go_testify

import (
	"github.com/stretchr/testify/require"
	"testing"
)

type Object struct {
	Value string
}

func TestSomething(t *testing.T) {
	var object = Object{Value: "Something"}
	require := require.New(t)
	require.Equal(123, 123, "they should be equal")
	require.NotEqual(123, 456, "they should not be equal")
	require.Nil(nil)
	require.NotNil(t, object)
}
$ go test -v 004_test.go
=== RUN   TestSomething
--- PASS: TestSomething (0.00s)
PASS
ok      command-line-arguments  0.250s

4、mock package

mock包提供了一种用于轻松编写mock对象的机制,在编写测试代码时可以使用该机制来代替真实对象。

package go_testify

import (
	"fmt"
	"github.com/stretchr/testify/mock"
	"testing"
)

// Test objects
// MyMockedObject是一个模拟对象,它实现了一个接口,该接口描述了我正在测试的代码所依赖的对象
type MyMockedObject struct {
	mock.Mock
}

// DoSomething是MyMockedObject上的一个方法,它实现了一些接口,只记录活动,并返回Mock对象告诉的内容
// 在真实的对象中,这个方法会做一些有用的事情,但由于这是一个模拟对象,我们只需要将其截断
func (m *MyMockedObject) DoSomething(number int) (bool, error) {
	args := m.Called(number)
	return args.Bool(0), args.Error(1)
}

func targetFuncThatDoesSomethingWithObj1(myMockedObject *MyMockedObject) (bool, error) {
	b, err := myMockedObject.DoSomething(123)
	if err != nil {
		return false, fmt.Errorf("failed, error details: %w", err)
	}
	return b, nil
}

// 实际测试功能
// TestSomething是一个如何使用我们的测试对象来断言我们正在测试的一些目标代码的示例
func TestSomething(t *testing.T) {
	testObj := new(MyMockedObject)
	testObj.On("DoSomething", 123).Return(true, nil)
	targetFuncThatDoesSomethingWithObj1(testObj)
	testObj.AssertExpectations(t)
}

// TestSomethingWithPlaceholder是关于如何使用我们的测试对象来断言我们正在测试的一些目标代码的第二个例子
// 这次使用占位符,当传入的数据通常是动态生成的,并且无法预先预测时可能会使用占位符
func TestSomethingWithPlaceholder(t *testing.T) {
	testObj := new(MyMockedObject)
	testObj.On("DoSomething", mock.Anything).Return(true, nil)
	targetFuncThatDoesSomethingWithObj2(testObj)
	testObj.AssertExpectations(t)
}

func targetFuncThatDoesSomethingWithObj2(myMockedObject *MyMockedObject) (bool, error) {
	b, err := myMockedObject.DoSomething(123)
	if err != nil {
		return false, fmt.Errorf("failed, error details: %w", err)
	}
	return b, nil
}

// 展示了如何使用Unset方法清理处理程序,然后添加新的处理程序
func TestSomethingElse2(t *testing.T) {
	testObj := new(MyMockedObject)
	mockCall := testObj.On("DoSomething", mock.Anything).Return(true, nil)
	targetFuncThatDoesSomethingWithObj3(testObj)
	testObj.AssertExpectations(t)
	mockCall.Unset()
	testObj.On("DoSomething", mock.Anything).Return(false, nil)
	testObj.AssertExpectations(t)
}

func targetFuncThatDoesSomethingWithObj3(myMockedObject *MyMockedObject) (bool, error) {
	b, err := myMockedObject.DoSomething(123)
	if err != nil {
		return false, fmt.Errorf("failed, error details: %w", err)
	}
	return b, nil
}
$ go test -v 005_test.go
=== RUN   TestSomething
    005_test.go:36: PASS:       DoSomething(int)
--- PASS: TestSomething (0.00s)
=== RUN   TestSomethingWithPlaceholder
    005_test.go:45: PASS:       DoSomething(string)
--- PASS: TestSomethingWithPlaceholder (0.00s)
=== RUN   TestSomethingElse2
    005_test.go:61: PASS:       DoSomething(string)
    005_test.go:64: PASS:       DoSomething(string)
--- PASS: TestSomethingElse2 (0.00s)
PASS
ok      command-line-arguments  0.262s

5、suite package

suite 包您可以使用结构体构建测试套件,在结构体上定义设置/拆卸和测试方法,并像平常一样使用 go test 运行

它们。

package go_testify

import (
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"
)

type ExampleTestSuite struct {
	suite.Suite
	VariableThatShouldStartAtFive int
}

// before each test
func (suite *ExampleTestSuite) SetupTest() {
	suite.VariableThatShouldStartAtFive = 5
}

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

func TestExampleTestSuite(t *testing.T) {
	suite.Run(t, new(ExampleTestSuite))
}
$ go test -v 006_test.go
=== RUN   TestExampleTestSuite
=== RUN   TestExampleTestSuite/TestExample
--- PASS: TestExampleTestSuite (0.00s)
    --- PASS: TestExampleTestSuite/TestExample (0.00s)
PASS
ok      command-line-arguments  0.371s

要获得一个更完整的示例,使用 suite 包提供的所有功能,请查看我们的示例测试suite :文章来源地址https://www.toymoban.com/news/detail-493341.html

package go_testify

import (
	"testing"
	"github.com/stretchr/testify/suite"
)

type ExampleTestSuite struct {
	suite.Suite
	VariableThatShouldStartAtFive int
}

// before each test
func (suite *ExampleTestSuite) SetupTest() {
	suite.VariableThatShouldStartAtFive = 5
}

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

func TestExampleTestSuite(t *testing.T) {
	suite.Run(t, new(ExampleTestSuite))
}
$ go test -v 007_test.go
=== RUN   TestExampleTestSuite
=== RUN   TestExampleTestSuite/TestExample
--- PASS: TestExampleTestSuite (0.00s)
    --- PASS: TestExampleTestSuite/TestExample (0.00s)
PASS
ok      command-line-arguments  0.036s

6、常用的stretchr/testify框架函数

func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool

func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool

func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool

func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool
func Error(t TestingT, err error, msgAndArgs ...interface{}) bool

func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool
func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool

func True(t TestingT, value bool, msgAndArgs ...interface{}) bool
func False(t TestingT, value bool, msgAndArgs ...interface{}) bool

func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool

func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool)
func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool)

func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool
func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool

到了这里,关于Go语言测试库stretchr/testify的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Go语言的单元测试与基准测试详解

    单元测试 以一个加法函数为例,对其进行单元测试。 首先编写add.go文件: 其次编写add_test.go文件,在go语言中,测试文件均已_test结尾,这里只需要在被测试的文件后加上_test即可。并且测试文件与要被测试的文件需要放在同一个包中,并不像 Java 那样需要将所有的测试文件

    2024年02月03日
    浏览(38)
  • 【go语言开发】编写单元测试

    本文主要介绍使用go语言编写单元测试用例,首先介绍如何编写单元测试,然后介绍基本命令的使用,最后给出demo示例 在go语言中编写单元测试时,使用说明 测试文件命名 :在 Go 语言中,测试文件的命名应与被测试的源代码文件相同,但以 “_test” 结尾。例如,如果你的源

    2024年02月04日
    浏览(38)
  • 【go语言】3.3.1 单元测试和基准测试

    Go 语言的 testing 包为编写单元测试和基准测试提供了强大的支持。单元测试用于验证代码的正确性,基准测试用于测量代码的性能。 在Go语言中,单元测试和基准测试是两种常用的测试方法,用于测试和评估代码的质量和性能。 单元测试是一种针对代码中最小可测试单元(函

    2024年02月08日
    浏览(37)
  • 7 文件操作、单元测试、goroutine【Go语言教程】

    1.1 介绍 os.File 封装所有文件相关操作,File 是一个结构体 常用方法: 打开文件 关闭文件 1.2 应用实例 ①读文件 常用方法: ①bufio.NewReader(), reader.ReadString【带缓冲】 ②io/ioutil【一次性读取,适用于小文件】 读取文件的内容并显示在终端(带缓冲区的方式),使用 os.Open, file.

    2024年02月04日
    浏览(46)
  • 36-代码测试(上):如何编写Go语言单元测试和性能测试用例?

    每种语言通常都有自己的测试包/模块,Go语言也不例外。在Go中,我们可以通过 testing 包对代码进行单元测试和性能测试。  Go语言有自带的测试框架 testing ,可以用来实现单元测试(T类型)和性能测试(B类型),通过 go test 命令来执行单元测试和性能测试。 go test 执行测试

    2024年04月11日
    浏览(40)
  • Go语言工程实践之测试与Gin项目实践

    回归 测试 一般是QA(质量保证)同学 手动通过终端回归一些固定的主流程 场景 集成 测试 是对 系统功能维度做测试验证 ,通过服务暴露的某个接口,进行自动化测试 而 单元 测试 开发阶段,开发者 对单独的函数、模块做功能验证 层级从上至下, 测试成本逐渐减低 ,而测试 覆

    2024年02月13日
    浏览(40)
  • Fabric使用自己的链码进行测试-go语言

    书接前文 Fabric链码部署-go语言 通过上面这篇文章,你可以部署好自己的链码 (后面很多命令是否需要修改,都是根据上面这篇文章来的,如果零基础的话建议先看上面这篇) 就进行下一步 在测试网络上运行自己的链码 目录 1、导航到test-network目录 1.1 打开日志Logspout(可选

    2024年02月05日
    浏览(34)
  • Go语言基准测试(benchmark)三部曲之一:基础篇

    这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos Go的标准库内置的testing框架提供了基准测试(benchmark)功能,可以用来验证本地方法在串行或者并行执行时的基准表现,帮助开发者了解代码的真实性能情况,例如一个方法执行一次的平均耗时,还能

    2024年02月06日
    浏览(41)
  • Go语言基准测试(benchmark)三部曲之三:提高篇

    这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos -《Go语言基准测试(benchmark)三部曲》已近尾声,经历了《基础篇》和《内存篇》的实战演练,相信您已熟练掌握了基准测试的常规操作以及各种参数的用法,现在可以学习一些进阶版的技能了,在面

    2024年02月06日
    浏览(33)
  • 【字节跳动青训营】后端笔记整理-3 | Go语言工程实践之测试

    **本人是第六届字节跳动青训营(后端组)的成员。本文由博主本人整理自该营的日常学习实践,首发于稀土掘金:🔗Go语言工程实践之测试 | 青训营 目录 一、概述 1、回归测试 2、集成测试 3、单元测试 二、单元测试 1、流程 2、规则 3、单元测试的例子 4、assert 5、覆盖率

    2024年02月15日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包