当使用数据库事务时,如何编写单元测试?

huangapple go评论74阅读模式
英文:

How to write unit test when using db transaction?

问题

在你的项目中使用MySQL事务时,你想知道如何编写数据库事务的单元测试。例如:

func SomeFunc() error {
  return db.Transaction(func(tx *gorm.DB) {
    // 以下是我的业务逻辑
    tx.Select(xxx)
    tx.Create(xxx)
    tx.Delete(xxx)
  }) 
}

我认为你对gorm有很强的依赖,这可能不太好。你是否需要为单元测试定义一个事务接口?

英文:

I'm using mysql transaction in my project, I want to know how to write unit test when using db transaction? for example:

func SomeFunc() error {
  return db.Transaction(func(tx *gorm.DB) {
    // my business logic goes below
    tx.Select(xxx)
    tx.Create(xxx)
    tx.Delete(xxx)
  }) 
}

What's I think is that I rely on gorm strongly, that's may be bad. Do I need to define a trancation interface for only unit test?

答案1

得分: 2

一种在测试数据库时编写测试的方法是始终使用内存数据库进行测试,或者使用带有虚假数据的真实数据库。我鼓励你以这种方式编写测试,而不是单元测试,因为在单元测试中,你所测试的都是你编写的虚假或假数据。以下是我所说的一个示例:

import (
    "testing"
    "database/sql"
    _ "github.com/mattn/go-sqlite3" // 导入sqlite驱动
)

func TestMyFunction(t *testing.T) {
    db, err := sql.Open("sqlite3", ":memory:") // 使用内存中的sqlite数据库进行测试
    if err != nil {
        t.Fatal(err)
    }
    defer db.Close()

    tx, err := db.Begin()
    if err != nil {
        t.Fatal(err)
    }
    defer tx.Rollback() // 在测试结束时回滚事务

    // 在事务中执行你要测试的代码
    // ...

    err = tx.Commit() // 如果没有错误,则提交事务
    if err != nil {
        t.Fatal(err)
    }

    // 检查你要测试的代码的结果
    // ...
}

希望对你有帮助!

英文:

one way to write a test when you have to test a database is always to bring up an in-memory database to test it or a real database with fake data I encourage you to write tests in this way not unit tests because in unit tests all your testing is the fake or dummy that you write here is an example of what I mean:

import (
    "testing"
    "database/sql"
    _ "github.com/mattn/go-sqlite3" // import the sqlite driver
)

func TestMyFunction(t *testing.T) {
    db, err := sql.Open("sqlite3", ":memory:") // use an in-memory sqlite database for testing
    if err != nil {
        t.Fatal(err)
    }
    defer db.Close()

tx, err := db.Begin()
if err != nil {
    t.Fatal(err)
}
defer tx.Rollback() // rollback the transaction at the end of the test

// Execute your code under test within the transaction
// ...

err = tx.Commit() // commit the transaction if there were no errors
if err != nil {
    t.Fatal(err)
}

// Check the results of your code under test
// ...

}

huangapple
  • 本文由 发表于 2023年4月14日 21:54:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76015856.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定