当前位置: 首页 > 工具软件 > Testify > 使用案例 >

【golang】go mock单元测试stretchr/testify

钱远
2023-12-01

assert package

The assert package provides some helpful methods that allow you to write better test code in Go.

  • Prints friendly, easy to read failure descriptions
  • Allows for very readable code
  • Optionally annotate each assertion with a message

require package 

      The require package provides same global functions as the assert package, but instead of returning a boolean result they terminate current test.

mock package

     The mock package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code.

      An example test function that tests a piece of code that relies on an external object testObj, can setup expectations (testify) and assert that they indeed happened:

suite package

       The suite package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal.

 

准备工作

go get github.com/stretchr/testify

go get github.com/vektra/mockery/.../

       github.com/stretchr/testify/suite     github.com/stretchr/testify/mock

 

示例

package main

import (
	"fmt"
)

func Cal(x int) (result int) {
	return x + 2
	
}

func main() {
	fmt.Println("Hello World")
}

 测试用例

package main

import (
	"testing"
)

func TestCal(t *testing.T) {
	if Cal(2) != 4 {
		t.Error("Expected 2 + 2 to equal 4")
	}
}

 

 

 

 类似资料: