当前位置:网站首页>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
)
边栏推荐
- 实现CNN图像的识别和训练通过tensorflow框架对cifar10数据集等方法的处理
- Ocean CMS vulnerability - search php
- SQL Injection (GET/Search)
- [机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心
- MySQL 数据处理值增删改
- PhpMyAdmin stage file contains analysis traceability
- Spark实战1:单节点本地模式搭建Spark运行环境
- Today's sleep quality record 77 points
- JS convert pseudo array to array
- 树的深入和广度优先遍历(不考虑二叉树)
猜你喜欢
SQL Injection (GET/Select)
[sort] bucket sort
logback日志的整理
又一个行业被中国芯片打破空白,难怪美国模拟芯片龙头降价抛售了
Flutter dynamic | fair 2.5.0 new version features
Mobile phones and computers can be used, whole people, spoof code connections, "won't you Baidu for a while" teach you to use Baidu
Golang — 命令行工具cobra
Box layout of Kivy tutorial BoxLayout arranges sub items in vertical or horizontal boxes (tutorial includes source code)
Comprehensive evaluation of double chain notes remnote: fast input, PDF reading, interval repetition / memory
Brief analysis of tensorboard visual processing cases
随机推荐
The solution of Chinese font garbled code in keil5
Can newly graduated European college students get an offer from a major Internet company in the United States?
pytorch 载入历史模型时更换gpu卡号,map_location设置
[redis] cache warm-up, cache avalanche and cache breakdown
When updating mysql, the condition is a query
Halcon combined with C # to detect surface defects -- Halcon routine autobahn
Swiftui development experience: the five most powerful principles that a programmer needs to master
Resource Cost Optimization Practice of R & D team
CVPR 2022 | interpretation of 6 excellent papers selected by meituan technical team
Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:
windos 创建cordova 提示 因为在此系统上禁止运行脚本
Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
Box layout of Kivy tutorial BoxLayout arranges sub items in vertical or horizontal boxes (tutorial includes source code)
Use docker to build sqli lab environment and upload labs environment, and the operation steps are provided with screenshots.
Leetcode-1175.Prime Arrangements
Complete DNN deep neural network CNN training with tensorflow to complete image recognition cases
mysql中的字段问题
Logseq evaluation: advantages, disadvantages, evaluation, learning tutorial
使用tensorflow进行完整的DNN深度神经网络CNN训练完成图片识别案例
软件测试工作那么难找,只有外包offer,我该去么?