如何正确设置go-sqlmock的模拟行和查询

pkbketx9  于 2023-01-03  发布在  Go
关注(0)|答案(2)|浏览(144)

我正在golang中设置测试。
我使用go-sqlmock来测试mysql连接。
但是sqlmock.NewRowsmock.ExpectQuery在有错误的情况下不能很好地工作。
我想知道如何解决此错误。

server side: golang
db: mysql
web framework: gin

dao.go

func GetSingleArticleDao(c *gin.Context, db *sql.DB) (util.Article, *sql.Rows) {
    id := c.Params.ByName("id")
    article := util.Article{}
    errArticle := db.QueryRow("SELECT * FROM articles WHERE id = ?", id).Scan(&article.ID, &article.UUID, &article.TITLE, &article.CONTENT)
    if errArticle != nil {
        panic(errArticle.Error())
    }
    rows, errImage := db.Query("SELECT image_name FROM images WHERE article_uuid  = ?", article.UUID)
    if errImage != nil {
        panic(errImage.Error())
    }

    return article, rows
}

dao_测试. go

func TestGetSingleArticleDao(t *testing.T) {
    db, mock, err := sqlmock.New()

    if err != nil {
        t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
    }

    defer db.Close()

    articleMockRows := sqlmock.NewRows([]string{"id", "uuid", "title", "content"}).
        AddRow("1", "bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c", "test", "test")

    mock.ExpectQuery("SELECT (.+) FROM articles where id=\\?").
        WithArgs("1").
        WillReturnRows(articleMockRows)

    imageMockRows := sqlmock.NewRows([]string{"article_uuid", "image_name"}).
        AddRow("bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c", "1a90696f-4fe7-48f5-81a5-ca72c129f4b0").
        AddRow("bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c", "3d997272-468f-4b66-91db-00c39f0ef717")

    mock.ExpectQuery("^SELECT (.+) FROM images*").
        WithArgs("bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c").
        WillReturnRows(imageMockRows)

    resp := httptest.NewRecorder()
    gin.SetMode(gin.TestMode)
    ctx, _ := gin.CreateTestContext(resp)

    article, imageRows := GetSingleArticleDao(ctx, db)

    for imageRows.Next() {
        imageName := util.ImageName{}
        err := imageRows.Scan(&imageName.NAME)
        if err != nil {
            panic(err.Error())
        }
        article.IMAGENAMES = append(article.IMAGENAMES, imageName)
    }

    expectedArticle := util.Article{
        ID:      1,
        UUID:    "bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c",
        TITLE:   "test",
        CONTENT: "test",
    }

    imageName1 := util.ImageName{
        NAME: "1a90696f-4fe7-48f5-81a5-ca72c129f4b0",
    }
    expectedArticle.IMAGENAMES = append(expectedArticle.IMAGENAMES, imageName1)

    imageName2 := util.ImageName{
        NAME: "3d997272-468f-4b66-91db-00c39f0ef717",
    }

    expectedArticle.IMAGENAMES = append(expectedArticle.IMAGENAMES, imageName2)

    assert.Equal(t, expectedArticle, article)
}

我希望go test -v运行没有错误。
但实际情况并非如此。
这里是错误。

$ go test -v 
=== RUN   TestGetSingleArticleDao
--- FAIL: TestGetSingleArticleDao (0.00s)
panic: Query: could not match actual sql: "SELECT * FROM articles WHERE id = ?" with expected regexp "SELECT (.+) FROM articles where id=\?" [recovered]
        panic: Query: could not match actual sql: "SELECT * FROM articles WHERE id = ?" with expected regexp "SELECT (.+) FROM articles where id=\?"

goroutine 34 [running]:
testing.tRunner.func1(0xc00022c000)
        /usr/local/go/src/testing/testing.go:830 +0x392
panic(0x165a960, 0xc0001bc4a0)
        /usr/local/go/src/runtime/panic.go:522 +0x1b5
article/api/dao.GetSingleArticleDao(0xc000214160, 0xc0002180c0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
        /Users/jpskgc/article/api/dao/dao.go:26 +0x35d
article/api/dao.TestGetSingleArticleDao(0xc00022c000)
        /Users/jpskgc/article/api/dao/dao_test.go:92 +0x750
testing.tRunner(0xc00022c000, 0x1788730)
        /usr/local/go/src/testing/testing.go:865 +0xc0
created by testing.(*T).Run
        /usr/local/go/src/testing/testing.go:916 +0x35a
exit status 2
FAIL    article/api/dao 0.030s
umuewwlo

umuewwlo1#

这是由以下部件引起的

resp := httptest.NewRecorder()
    gin.SetMode(gin.TestMode)
    ctx, _ := gin.CreateTestContext(resp)

我应该在ctx中添加"id" :"1"参数。
所以我把那部分改成了:

param := gin.Param{"id", "1"}
    params := gin.Params{param}
    req, _ := http.NewRequest("GET", "/article/1", nil)
    var context *gin.Context
    context = &gin.Context{Request: req, Params: params}
jgwigjjp

jgwigjjp2#

您可能需要使用regexp.QuoteMeta()来转义查询中的所有正则表达式元字符,而不是使用\\

mock.ExpectQuery(regexp.QuoteMeta("SELECT (.+) FROM articles FROM articles WHERE id = ?")).
            WithArgs("1").
            WillReturnRows(articleMockRows)

只是一个小提示,而不是这样做:

mock.ExpectQuery("SELECT (.+) FROM articles where id=\\?").
        WithArgs("1").
        WillReturnRows(articleMockRows)

您可以尝试这样做:

mock.ExpectQuery("SELECT (.+) FROM articles").
        WithArgs("1").
        WillReturnRows(articleMockRows)

这取决于你想在查询中检查什么,但对我来说,最重要的是检查我的查询是否选择了正确的表。我通常不关心使用哪个属性来过滤数据。如果你认为过滤器很重要,那么,这里还有一些例子:

相关问题