猿问

如何使用 gorm 进行单元测试

我是新来的和.在我的项目中,我正在使用和连接数据库。Gounit testGogormmysql

我的查询是如何对我的代码进行单元测试的:

main_test:


package main


import (

    "log"

    "os"

    "testing"


    "github.com/jinzhu/gorm"

    _ "github.com/jinzhu/gorm/dialects/mysql"

)


func TestinitDB(m *testing.M) {

    dataSourceName := "root:@tcp(localhost:3306)/?parseTime=True"

    db, err := gorm.Open("mysql", dataSourceName)


    if err != nil {

        log.Fatal("failed to connect database")

    }

    //db.Exec("CREATE DATABASE test")

    db.LogMode(true)

    db.Exec("USE test111")

    os.Exit(m.Run())

}

请帮我写单元测试文件



侃侃无极
浏览 353回答 2
2回答

慕哥6287543

“如何进行单元测试”是一个非常广泛的问题,因为它取决于你想要测试什么。在您的示例中,您正在处理与数据库的远程连接,这通常是在单元测试中被嘲笑的东西。目前尚不清楚这是否是您要寻找的,也不是必需的。通过看到你使用不同的数据库,我希望其意图不是嘲笑。首先看看这篇文章,它已经回答了你关于TestMain和打算如何工作的问题。testing.M您的代码当前所做的(如果您的测试名称正确命名)是在其他测试周围添加一个方法来执行设置和拆卸,但是您没有任何其他测试来使用此设置和拆卸,因此您将获得结果。TestMainno tests to run这不是你问题的一部分,但我建议尽量避免,直到你对测试Go代码有信心。使用和测试单独的单元可能更容易理解。你可以通过调用你的测试并让初始值设定项接受一个参数来实现几乎相同的事情。testing.Mtesting.TinitDB()func initDB(dbToUse string) {&nbsp; &nbsp; // ...&nbsp; &nbsp; db.Exec("USE "+dbToUse)}然后,您将从主文件和测试中调用。您可以在 pkg.go.dev/testing 阅读有关 Go 的测试包的信息,您还可以在其中找到 和 之间的差异。initDB("test")initDB("test111")testing.Ttesting.M下面是一个简短的示例,其中包含一些基本测试,这些测试不需要任何设置或拆卸,而是使用 代替 。testing.Ttesting.M主要.gopackage mainimport "fmt"func main() {&nbsp; &nbsp; fmt.Println(add(1, 2))}func add(a, b int) int {&nbsp; &nbsp; return a + b}main_testpackage mainimport "testing"func TestAdd(t *testing.T) {&nbsp; &nbsp; t.Run("add 2 + 2", func(t *testing.T) {&nbsp; &nbsp; &nbsp; &nbsp; want := 4&nbsp; &nbsp; &nbsp; &nbsp; // Call the function you want to test.&nbsp; &nbsp; &nbsp; &nbsp; got := add(2, 2)&nbsp; &nbsp; &nbsp; &nbsp; // Assert that you got your expected response&nbsp; &nbsp; &nbsp; &nbsp; if got != want {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t.Fail()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })}此测试将测试您的方法,并确保它在作为参数传递时返回正确的值。使用 是可选的,但它会为您创建一个子测试,这使得读取输出更容易一些。add2, 2t.Run由于在包级别进行测试,因此,如果不以递归方式使用三点格式(包括每个包),则需要指定要测试的包。若要运行上述示例中的测试,请指定包和详细输出。-v$ go test ./ -v=== RUN&nbsp; &nbsp;TestAdd=== RUN&nbsp; &nbsp;TestAdd/add_2_+_2--- PASS: TestAdd (0.00s)&nbsp; &nbsp; --- PASS: TestAdd/add_2_+_2 (0.00s)PASSok&nbsp; &nbsp; &nbsp; x&nbsp; &nbsp; &nbsp; &nbsp;(cached)围绕这个主题还有很多东西需要学习,比如测试框架和测试模式。例如,测试框架testify可以帮助您进行断言,并在测试失败时打印出漂亮的输出,并且表驱动的测试是Go中非常常见的模式。您还在编写HTTP服务器,该服务器通常需要额外的测试设置才能正确测试。幸运的是,标准库中的包带有一个名为httptest的子包,它可以帮助您记录外部请求或为外部请求启动本地服务器。还可以通过使用手动构造的请求直接调用处理程序来测试处理程序。http它看起来像这样。func TestSomeHandler(t *testing.T) {&nbsp; &nbsp; // Create a request to pass to our handler. We don't have any query parameters for now, so we'll&nbsp; &nbsp; // pass 'nil' as the third parameter.&nbsp; &nbsp; req, err := http.NewRequest("GET", "/some-endpoint", nil)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; t.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.&nbsp; &nbsp; rr := httptest.NewRecorder()&nbsp; &nbsp; handler := http.HandlerFunc(SomeHandler)&nbsp; &nbsp; // Our handlers satisfy http.Handler, so we can call their ServeHTTP method&nbsp;&nbsp; &nbsp; // directly and pass in our Request and ResponseRecorder.&nbsp; &nbsp; handler.ServeHTTP(rr, req)&nbsp; &nbsp; // Check the status code is what we expect.&nbsp; &nbsp; if status := rr.Code; status != http.StatusOK {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("handler returned wrong status code: got %v want %v",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; status, http.StatusOK)&nbsp; &nbsp; }现在,测试一些代码。我们可以运行 init 方法,并使用响应记录器调用您的任何服务。package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "net/http/httptest"&nbsp; &nbsp; "testing")func TestGetAllJobs(t *testing.T) {&nbsp; &nbsp; // Initialize the DB&nbsp; &nbsp; initDB("test111")&nbsp; &nbsp; req, err := http.NewRequest("GET", "/GetAllJobs", nil)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; t.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; rr := httptest.NewRecorder()&nbsp; &nbsp; handler := http.HandlerFunc(GetAllJobs)&nbsp; &nbsp; handler.ServeHTTP(rr, req)&nbsp; &nbsp; // Check the status code is what we expect.&nbsp; &nbsp; if status := rr.Code; status != http.StatusOK {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("handler returned wrong status code: got %v want %v",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; status, http.StatusOK)&nbsp; &nbsp; }&nbsp; &nbsp; var response []Jobs&nbsp; &nbsp; if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("got invalid response, expected list of jobs, got: %v", rr.Body.String())&nbsp; &nbsp; }&nbsp; &nbsp; if len(response) < 1 {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("expected at least 1 job, got %v", len(response))&nbsp; &nbsp; }&nbsp; &nbsp; for _, job := range response {&nbsp; &nbsp; &nbsp; &nbsp; if job.SourcePath == "" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("expected job id %d to&nbsp; have a source path, was empty", job.JobID)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

小怪兽爱吃肉

你可以使用 go-sqlmock:&nbsp; &nbsp; package mainimport (&nbsp; &nbsp; "database/sql"&nbsp; &nbsp; "regexp"&nbsp; &nbsp; "testing"&nbsp; &nbsp; "gopkg.in/DATA-DOG/go-sqlmock.v1"&nbsp; &nbsp; "gorm.io/driver/postgres"&nbsp; &nbsp; "gorm.io/gorm")type Student struct {&nbsp; &nbsp; //*gorm.Model&nbsp; &nbsp; Name string&nbsp; &nbsp; ID string}type v2Suite struct {&nbsp; &nbsp; db&nbsp; &nbsp; &nbsp; *gorm.DB&nbsp; &nbsp; mock&nbsp; &nbsp; sqlmock.Sqlmock&nbsp; &nbsp; student Student}func TestGORMV2(t *testing.T) {&nbsp; &nbsp; s := &v2Suite{}&nbsp; &nbsp; var (&nbsp; &nbsp; &nbsp; &nbsp; db&nbsp; *sql.DB&nbsp; &nbsp; &nbsp; &nbsp; err error&nbsp; &nbsp; )&nbsp; &nbsp; db, s.mock, err = sqlmock.New()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("Failed to open mock sql db, got error: %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; if db == nil {&nbsp; &nbsp; &nbsp; &nbsp; t.Error("mock db is null")&nbsp; &nbsp; }&nbsp; &nbsp; if s.mock == nil {&nbsp; &nbsp; &nbsp; &nbsp; t.Error("sqlmock is null")&nbsp; &nbsp; }&nbsp; &nbsp; dialector := postgres.New(postgres.Config{&nbsp; &nbsp; &nbsp; &nbsp; DSN:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "sqlmock_db_0",&nbsp; &nbsp; &nbsp; &nbsp; DriverName:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"postgres",&nbsp; &nbsp; &nbsp; &nbsp; Conn:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;db,&nbsp; &nbsp; &nbsp; &nbsp; PreferSimpleProtocol: true,&nbsp; &nbsp; })&nbsp; &nbsp; s.db, err = gorm.Open(dialector, &gorm.Config{})&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("Failed to open gorm v2 db, got error: %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; if s.db == nil {&nbsp; &nbsp; &nbsp; &nbsp; t.Error("gorm db is null")&nbsp; &nbsp; }&nbsp; &nbsp; s.student = Student{&nbsp; &nbsp; &nbsp; &nbsp; ID:&nbsp; &nbsp;"123456",&nbsp; &nbsp; &nbsp; &nbsp; Name: "Test 1",&nbsp; &nbsp; }&nbsp; &nbsp; defer db.Close()&nbsp; &nbsp; s.mock.MatchExpectationsInOrder(false)&nbsp; &nbsp; s.mock.ExpectBegin()&nbsp; &nbsp; s.mock.ExpectQuery(regexp.QuoteMeta(&nbsp; &nbsp; &nbsp; &nbsp; `INSERT INTO "students" ("id","name")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; VALUES ($1,$2) RETURNING "students"."id"`)).&nbsp; &nbsp; WithArgs(s.student.ID, s.student.Name).&nbsp; &nbsp; WillReturnRows(sqlmock.NewRows([]string{"id"}).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; AddRow(s.student.ID))&nbsp; &nbsp; s.mock.ExpectCommit()&nbsp; &nbsp; if err = s.db.Create(&s.student).Error; err != nil {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("Failed to insert to gorm db, got error: %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; err = s.mock.ExpectationsWereMet()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("Failed to meet expectations, got error: %v", err)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答