寫測試用例的, 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: [email protected]
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: [email protected]
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 ...
}