go中的test

package main

//每一个test文件必须引入testing的包
import (
	"testing"
	"fmt"
)
//测试用例必须以Test开始,否则不会执行
func eee(t *testing.T) {
	res:=Print1to20()
	if 20 != res{
		fmt.Println("wrong in test")
		return
	}
	fmt.Println("right in test")
}



func TestPrint1to20No1(t *testing.T) {
	//SkipNow  跳过当前test 直接按PASS处理 并继续执行下一个test
	//并且在代码块的第一行
	t.SkipNow()
	res:=Print1to20()
	if 20 != res{
		fmt.Println("wrong in test in 1th")
		return
	}
	fmt.Println("right in test  in 1th")
}

func TestPrint1to20No2(t *testing.T) {
	res:=Print1to20()
	if 20 != res{
		fmt.Println("wrong in test in 2th")
		return
	}
	fmt.Println("right in test  in 2th")
}


func TestSubTest2(t *testing.T) {

	fmt.Println("Test Sub Test2")
}

func TestSubTest1(t *testing.T) {

	fmt.Println("Test Sub Test1")
}
//控制子测试的测试顺序  t.Run()
func TestMultySubTest(t *testing.T) {
	t.Run("t1",TestSubTest1)
	t.Run("t2",TestSubTest2)
}

//使用TestMain作为初始化test,并且使用m.Run()来调用其他test
//完成一些需要初始化的test,例如数据库连接,文件打开,预先登陆
func TestMain(m *testing.M){
	fmt.Println("this is TestMain")
	//调用整个测试文件里的其他test,如果没有 m.Run()  则只会执行自己
	m.Run()
}
//benchmark 也是一个普通的test case 受到  TestMain的控制
//b.N受到被测程序稳态 的影响
func BenchmarkPrint1to20(b *testing.B) {
	for i:=0;i<b.N;i++{
		Print1to20()
	}
}

this is TestMain
goos: windows
goarch: amd64
pkg: stream-action/1test
100000000	        13.8 ns/op
PASS

Process finished with exit code 0

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Go ,`httptest` 包是用于编写 HTTP 测试的一个标准库。它提供了一些工具和函数,用于模拟 HTTP 请求和处理 HTTP 响应,以进行单元测试和集成测试。 下面是一个示例,演示如何使用 `httptest` 进行 HTTP 测试: ```go package main import ( "net/http" "net/http/httptest" "testing" ) func MyHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("Hello, World!")) } func TestMyHandler(t *testing.T) { req, err := http.NewRequest("GET", "/hello", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(MyHandler) handler.ServeHTTP(rr, req) if rr.Code != http.StatusOK { t.Errorf("Expected status code %d, but got %d", http.StatusOK, rr.Code) } expectedBody := "Hello, World!" if rr.Body.String() != expectedBody { t.Errorf("Expected response body %q, but got %q", expectedBody, rr.Body.String()) } } ``` 在上述示例,我们定义了一个名为 `MyHandler` 的 HTTP 处理函数。然后,我们使用 `httptest.NewRecorder()` 创建一个 ResponseRecorder 对象 `rr`,它可以用来捕获处理函数的输出。接下来,我们使用 `http.NewRequest()` 创建一个模拟的 HTTP 请求对象 `req`。最后,我们使用 `handler.ServeHTTP(rr, req)` 将请求发送到处理函数,并将响应记录到 `rr`。 在测试函数 `TestMyHandler` ,我们可以使用 `testing.T` 的方法来检查处理函数的行为。我们可以检查返回的状态码、响应体等内容,以确保处理函数按预期工作。 你可以根据你的具体需求和场景,在测试使用 `httptest` 包来模拟 HTTP 请求和检查处理函数的行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值