go 里的测试模式包含单元测试卷、系统测试和功能测试。单元测试卷认证单独函数公式,不依附政府资源;系统测试认证部件互动,包含政府资源;特性测试测量实施时间和能源消耗,可以使用 testing/quick 或 benchee 包。实战案例 中,大家需要结合这三种测试模式,为 crud 实际操作保证应用程序的稳定性。
探寻 Go 架构中常用的测试模式与实践单元测试卷在 Go 中,单元测试卷通常采用 testing 包。单元测试卷认证程序代码单独函数公式或方法,而不依附政府资源。
import "testing"
func TestAdd(t testing.T) {
tests := []struct {
a, b int
want int
}{
{1, 2, 3},
{-5, 10, 5},
}
for _, test := range tests {
got := Add(test.a, test.b)
if got != test.want {
t.Errorf("Add(%d, %d) = %d; want %d", test.a, test.b, got, test.want)
}
}
}
系统测试集成测试认证好几个部件的交互,通常包括政府资源,比如数据库系统或 HTTP 服务项目。在 Go 中,系统测试通常采用 go test -integration 标示。
package main
import (
"context"
"net/http/httptest"
"testing"
"github.com/gorilla/mux"
)
func TestHomeHandler(t testing.T) {
// 设置路由器和 HTTP 处理程序流程
router := mux.NewRouter()
router.HandleFunc("/", HomeHandler)
// 建立测试服务器
rr := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatalf("Could not create request: %v", err)
}
// 实行 HTTP 要求
router.ServeHTTP(rr, req)
// 查验回应情况
if status := rr.Code; status != 200 {
t.Errorf("HomeHandler returned wrong status code: got %v want %v", status, http.StatusOK)
}
// 查验回应具体内容
if rr.Body.String() != "Hello, world!" {
t.Errorf("HomeHandler returned wrong body: got %v want %v", rr.Body.String(), "Hello, world!")
}
}
func main() {
ctx := context.Background()
if err := startServer(ctx); err != nil {
log.Fatalf("Could not start server: %v", err)
}
}
功能测试性能测试考量编码在一定负荷中的实施时间和能源消耗。在 Go 中可以用 testing/quick 包(https://github.com/ardanlabs/gotraining/blob/master/topics/go/testing/performance/quick/main.go)实现快速功能测试,或者使用更高级别的包,比如 benchee(https://github.com/rwxrob/benchee)进行分析。
实战案例 考虑到一个简单的 Go 应用软件,用以对用户进行 CRUD(建立、载入、升级和删除)实际操作。我们可以用下列测试模式:
单元测试卷:检测单独函数公式或方法,比如客户建立或用户升级。 系统测试:检测应用软件与数据库系统的交互,比如创建用户或获得每个用户。 功能测试:应用特殊负荷和时间测量应用程序的实行,比如很多建立或载入客户。通过结合这种测试模式,大家能够确保应用软件在不同的场景下表现优异。
以上就是关于探寻 Go 架构中常用的测试模式与实践的详细内容,大量欢迎关注其他类似文章!