一、web测试
package webTest
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
}
//测试web
func TestConn(t *testing.T) {
recorder := httptest.NewRequest("GET", "http://example.com/foo", nil)
newRecorder := httptest.NewRecorder()
helloHandler(newRecorder,recorder)
bytes, err := ioutil.ReadAll(newRecorder.Result().Body)
if err != nil {
fmt.Println("bytes err:",err)
return
}
if string(bytes) != "hello world" {
t.Fatal("expected hello word,but got",string(bytes))
}
}
//批量测试web
func BenchmarkHello(b *testing.B) {
//重置时间
b.ResetTimer()
for i := 0; i < b.N; i++ {
recorder := httptest.NewRequest("GET", "http://example.com/foo", nil)
newRecorder := httptest.NewRecorder()
helloHandler(newRecorder,recorder)
bytes, err := ioutil.ReadAll(newRecorder.Result().Body)
if err != nil {
fmt.Println("bytes err:",err)
return
}
if string(bytes) != "hello world" {
b.Fatal("expected hello word,but got",string(bytes))
}
}
}