当前位置:网站首页>Go language unit test 5: go language uses go sqlmock and Gorm to do database query mock
Go language unit test 5: go language uses go sqlmock and Gorm to do database query mock
2022-07-03 13:47:00 【Lao Liu, you are so awesome】
One , Libraries required for installation
1,gorm Official website :
2, install gorm
[email protected]:~$ go get -u gorm.io/gorm
3,go-sqlmock The address of :
https://github.com/DATA-DOG/go-sqlmock
4, Install... From the command line go-sqlmock:
[email protected]:~$ go get -u github.com/DATA-DOG/go-sqlmock
explain : Liu Hongdi's go The forest is a focus golang The blog of ,
Address :https://blog.csdn.net/weixin_43881017
explain : author : Liu Hongdi mailbox : [email protected]
Two , Information about the demonstration project
1, Address :
https://github.com/liuhongdi/unittest04
2, Functional specifications : Demonstrates the use of sqlmock Simulate the data records of the database
3, Project structure : Pictured :
3、 ... and ,go Code instructions
1,global/db.go
package global
import (
"gorm.io/gorm"
"time"
"gorm.io/driver/mysql"
)
var (
DBLink *gorm.DB
)
// establish mysql link
func SetupDBLink() (error) {
var err error
dsn:="root:[email protected](127.0.0.1:3306)/business?charset=utf8&parseTime=True&loc=Local";
DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
//DBLink.Logger.LogMode(true)
if err != nil {
return err
}
sqlDB, err := DBLink.DB()
// SetMaxIdleConns Set the maximum number of connections in the free connection pool
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenConns Set the maximum number of open database connections
sqlDB.SetMaxOpenConns(30)
// SetConnMaxLifetime Set the maximum time that the connection can be reused
sqlDB.SetConnMaxLifetime(time.Hour)
return nil
}
2,controller/userController.go
package controller
import (
"github.com/liuhongdi/unittest04/global"
"github.com/liuhongdi/unittest04/model"
)
func GoodsOne(goodsId int) (*model.Goods, error) {
goodsOne:=&model.Goods{}
err := global.DBLink.Where("goodsId=?",goodsId).First(&goodsOne).Error
//fmt.Println(err)
if (err != nil) {
return nil,err
} else {
return goodsOne,nil
}
}
3,model/goods.go
package model
type Goods struct {
GoodsId int64 `gorm:"column:goodsId",json:"goodsid"` // Self increasing
GoodsName string `gorm:"column:goodsName",json:"goodsname"` //
Subject string `gorm:"column:subject",json:"subject"`
Price string `gorm:"column:price",json:"price"`
Stock int `gorm:"column:stock",json:"stock"`
}
func (Goods) TableName() string {
return "goods"
}
4,main.go
package main
import (
"fmt"
"github.com/liuhongdi/unittest04/controller"
"github.com/liuhongdi/unittest04/global"
"log"
)
// Define an addition method
func add(a, b int) int {
return a + b
}
func init() {
//mysql link
err := global.SetupDBLink()
if err != nil {
log.Fatalf("init.setupDBEngine err: %v", err)
}
}
func main() {
goods,err := controller.GoodsOne(1)
if (err != nil){
log.Fatalf("err:%v",err)
} else {
fmt.Println(goods)
}
}
5,main_test.go
package main
import (
"database/sql"
"errors"
"fmt"
"github.com/DATA-DOG/go-sqlmock"
"github.com/liuhongdi/unittest04/controller"
"github.com/liuhongdi/unittest04/global"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"log"
"testing"
)
var mock sqlmock.Sqlmock
// initialization
func init() {
// establish sqlmock
var err error
var db *sql.DB
db, mock, err = sqlmock.New()
if nil != err {
log.Fatalf("Init sqlmock failed, err %v", err)
}
// combination gorm、sqlmock
global.DBLink, err = gorm.Open(mysql.New(mysql.Config{
SkipInitializeWithVersion: true,
Conn: db,
}), &gorm.Config{})
if nil != err {
log.Fatalf("Init DB with sqlmock failed, err %v", err)
}
}
// Test the information of a product , Enable sqlmock, Put back the result set
func TestOneMockRes(t *testing.T) {
goodsId:=1
// Create database records
rows := sqlmock.NewRows([]string{"goodsId", "goodsName", "subject", "price", "stock"}).
AddRow(2, "Moonii Ceramic lunar lamp ", " This is a test product ", "5.32", "33")
mock.ExpectQuery("^SELECT \\* FROM `goods` WHERE goodsId=\\? ORDER BY `goods`.`goodsId` LIMIT 1").
WithArgs(goodsId).WillReturnRows(rows)
// perform
goods,err:=controller.GoodsOne(goodsId)
if (err != nil) {
t.Fatalf("goodsId: %d, err:%v", goodsId, err)
}else {
fmt.Println(goods)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("there were unfulfilled expectations: %s", err)
}
}
// Test the information of a product , Enable sqlmock, No result set
func TestOneMockNoRes(t *testing.T) {
goodsId:=1
// Create database records
rows := sqlmock.NewRows([]string{"goodsId", "goodsName", "subject", "price", "stock"})
//AddRow(2, "Moonii Ceramic lunar lamp ", " This is a test product ", "5.32", "33")
mock.ExpectQuery("^SELECT \\* FROM `goods` WHERE goodsId=\\? ORDER BY `goods`.`goodsId` LIMIT 1").
WithArgs(goodsId).WillReturnRows(rows)
// perform
goods,err:=controller.GoodsOne(goodsId)
if (err != nil) {
t.Fatalf("goodsId: %d, err:%v", goodsId, err)
}else {
fmt.Println(goods)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("there were unfulfilled expectations: %s", err)
}
}
// Test the information of a product , Enable sqlmock, Return database error
func TestOneMockError(t *testing.T) {
goodsId:=1
// Pass on sql
mock.ExpectQuery("^SELECT \\* FROM `goods` WHERE goodsId=\\? ORDER BY `goods`.`goodsId` LIMIT 1").
WithArgs(goodsId).WillReturnError(errors.New("some error"))
// perform
goods,err:=controller.GoodsOne(goodsId)
if (err != nil) {
t.Fatalf("goodsId: %d, err:%v", goodsId, err)
}else {
fmt.Println(goods)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("there were unfulfilled expectations: %s", err)
}
}
Four , The test results
Execute test command :
[email protected]:/data/go/unittest04# go test -v
return :
[email protected]:/data/go/unittest04# go test -v
=== RUN TestOneMockRes
&{2 Moonii Ceramic lunar lamp This is a test product 5.32 33}
--- PASS: TestOneMockRes (0.00s)
=== RUN TestOneMockNoRes
2021/02/01 10:20:56 /data/go/unittest04/controller/userController.go:10 record not found
[0.075ms] [rows:0] SELECT * FROM `goods` WHERE goodsId=1 ORDER BY `goods`.`goodsId` LIMIT 1
main_test.go:69: goodsId: 1, err:record not found
--- FAIL: TestOneMockNoRes (0.00s)
=== RUN TestOneMockError
2021/02/01 10:20:56 /data/go/unittest04/controller/userController.go:10 some error
[0.038ms] [rows:0] SELECT * FROM `goods` WHERE goodsId=1 ORDER BY `goods`.`goodsId` LIMIT 1
main_test.go:87: goodsId: 1, err:some error
--- FAIL: TestOneMockError (0.00s)
FAIL
exit status 1
FAIL github.com/liuhongdi/unittest04 0.012s
5、 ... and , View the version of the library :
module github.com/liuhongdi/unittest04
go 1.15
require (
gorm.io/driver/mysql v1.0.1
gorm.io/gorm v1.20.6
github.com/DATA-DOG/go-sqlmock v1.5.0
)
边栏推荐
- 双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
- Swiftui development experience: the five most powerful principles that a programmer needs to master
- Stack application (balancer)
- Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
- 掌握Cypress命令行选项,是真正掌握Cypress的基础
- mysql更新时条件为一查询
- Multi table query of MySQL - multi table relationship and related exercises
- [how to solve FAT32 when the computer is inserted into the U disk or the memory card display cannot be formatted]
- Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:
- Halcon combined with C # to detect surface defects -- Halcon routine autobahn
猜你喜欢
Introduction to the implementation principle of rxjs observable filter operator
Road construction issues
[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心
Logback log sorting
Error running 'application' in idea running: the solution of command line is too long
Brief analysis of tensorboard visual processing cases
[技術發展-24]:現有物聯網通信技術特點
logback日志的整理
Tutoriel PowerPoint, comment enregistrer une présentation sous forme de vidéo dans Powerpoint?
Resolved (error in viewing data information in machine learning) attributeerror: target_ names
随机推荐
Disruptor -- a high concurrency and high performance queue framework for processing tens of millions of levels
Field problems in MySQL
Task5: multi type emotion analysis
Go language unit test 3: go language uses gocovey library to do unit test
Open PHP error prompt under Ubuntu 14.04
MySQL 数据处理值增删改
Asp. Net core1.1 without project JSON, so as to generate cross platform packages
Task6: using transformer for emotion analysis
User and group command exercises
MySQL constraints
The reasons why there are so many programming languages in programming internal skills
[556. Next larger element III]
[how to solve FAT32 when the computer is inserted into the U disk or the memory card display cannot be formatted]
The solution of Chinese font garbled code in keil5
[技术发展-24]:现有物联网通信技术特点
[today in history] July 3: ergonomic standards act; The birth of pioneers in the field of consumer electronics; Ubisoft releases uplay
又一个行业被中国芯片打破空白,难怪美国模拟芯片龙头降价抛售了
Start signing up CCF C ³- [email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g
挡不住了,国产芯片再度突进,部分环节已进到4nm
The R language GT package and gtextras package gracefully and beautifully display tabular data: nflreadr package and gt of gtextras package_ plt_ The winloss function visualizes the win / loss values