AdSense

網頁

2022/2/22

Golang 使用go-sqlmock mock sql UPDATE

Go語言的go-sqlmock函式庫可對sql driver的行為做mock,也就是可返回mock的查詢結果。


下面範例使用go-sqlmock對SQL執行做mock來做單元測試。

範例環境:

  • Go 1.17


主程式

參考「Golang sql PostgreSQL修改範例」主程式main.go中修改函式UpdateEmployee()UpdateEmployeeReturnID()


測試程式

測試程式main_test.goTestUpdateEmployee()TestUpdateEmployeeReturnID()使用go-sqlmock對sql進行mock。

參考「Golang go-sqlmock API簡介」。

main_test.go

package main

import (
    "testing"

    "github.com/DATA-DOG/go-sqlmock"
)

func TestUpdateEmployee(t *testing.T) {
    db, mock, err := sqlmock.New()
    if err != nil {
        t.Fatalf("opening a stub database connection error=%s", err)
    }
    defer db.Close()

    mock.ExpectBegin()
    result := sqlmock.NewResult(0, 1)
    mock.ExpectExec("^UPDATE employee.+$").WillReturnResult(result)
    mock.ExpectCommit()
    err = UpdateEmployee(db, &Employee{})
    if err != nil {
        t.Errorf("Unexpected error %v", err)
    }
}

func TestUpdateEmployeeReturnID(t *testing.T) {
    db, mock, err := sqlmock.New()
    if err != nil {
        t.Fatalf("opening a stub database connection error=%s", err)
    }
    defer db.Close()

    mock.ExpectBegin()
    rows := sqlmock.NewRows([]string{"id"}).AddRow(1)
    mock.ExpectQuery("^UPDATE employee.+$").WillReturnRows(rows)
    mock.ExpectCommit()
    id, err := UpdateEmployeeReturnID(db, &Employee{})

    expected := int64(1)
    if id != expected {
        t.Errorf("Expected %v, but %v", expected, id)
    }
}

github


沒有留言:

AdSense