写测试用例的, github 地址: go-testfixtures/testfixtures
用于 go 语言开发 web 网站, 针对 SQL 数据库编写轻松的测试用例
思想源于 “Ruby on Rails”, 示例数据保存在 Fixture 文件夹中. 在执行测试之前,先清理测试数据库,同时将示例数据加载到数据库中.
该方法针对真实的数据库运行测试,而不是只依赖于模拟. 因为模拟的方式可能会出现无法被测试所捕获的错误情况.
安装:
导入:
import (
"github.com/go-testfixtures/testfixtures/v3"
)
使用:
创建 fixture 文件夹.文件夹中每个文件只包含单个表的数据,同时命名为 <table_name>.yml
.
目录结构为:
myapp/
myapp.go
myapp_test.go
...
fixtures/
posts.yml
comments.yml
tags.yml
posts_tags.yml
...
文件内容类似:
# comments.yml
- id: 1
post_id: 1
content: A comment...
author_name: John Doe
author_email: john@doe.com
created_at: 2020-12-31 23:59:59
updated_at: 2020-12-31 23:59:59
- id: 2
post_id: 2
content: Another comment...
author_name: John Doe
author_email: john@doe.com
created_at: 2020-12-31 23:59:59
updated_at: 2020-12-31 23:59:59
# ...
测试用例样本:
package myapp
import (
"database/sql"
_ "github.com/lib/pq"
"github.com/go-testfixtures/testfixtures/v3"
)
var (
db *sql.DB
fixtures *testfixtures.Loader
)
func TestMain(m *testing.M) {
var err error
// Open connection to the test database.
// Do NOT import fixtures in a production database!
// Existing data would be deleted.
db, err = sql.Open("postgres", "dbname=myapp_test")
if err != nil {
...
}
fixtures, err := testfixtures.New(
testfixtures.Database(db), // You database connection
testfixtures.Dialect("postgres"), // Available: "postgresql", "timescaledb", "mysql", "mariadb", "sqlite" and "sqlserver"
testfixtures.Directory("testdata/fixtures"), // the directory containing the YAML files
)
if err != nil {
...
}
os.Exit(m.Run())
}
func prepareTestDatabase() {
if err := fixtures.Load(); err != nil {
...
}
}
func TestX(t *testing.T) {
prepareTestDatabase()
// Your test here ...
}
func TestY(t *testing.T) {
prepareTestDatabase()
// Your test here ...
}
func TestZ(t *testing.T) {
prepareTestDatabase()
// Your test here ...
}