php editor Xinyi introduces to you the Gorm delete clause sqlmock test. Gorm is an excellent ORM framework in the Go language, and sqlmock is a testing tool for Gorm, used to simulate database operations. When developing Gorm, we often need to test the database deletion operation. At this time, we can use sqlmock to simulate the database deletion operation for unit testing and integration testing. This article will introduce you in detail how to use Gorm and sqlmock to test delete clauses, helping you better carry out database-related development work.
Question content
I have a gorm deleted and the result is returned:
expirationdate := time.now().utc().add(-(48 * time.hour)) var deletedusers users res := gormdb.withcontext(ctx). table("my_users"). clauses(clause.returning{columns: []clause.column{{name: "email"}}}). where("created_at < ?", expirationdate). delete(&deletedusers)
Tests with clauses now always fail. For example:
sqlMock.ExpectExec(`DELETE`) .WithArgs(expirationDate) .WillReturnResult(sqlmock.NewResult(1, 1))
Receive error:
'Calling query 'delete from "my_users" where created_at expected exec or execcontext where:\n - matches sql: 'delete'\n - with parameters:\n 0 - 2023-01-18 06:15:34.694274 0000 utc\n - should return results with:\n lastinsertid: 1\n rowsaffected: 1"
I tried many other sqlmock expectations but they had similar issues. Also, we have no return value in expectexec, only in expectquery... Does anyone have to test gorm queries with clauses?
SOLUTION
I was able to successfully manage your needs. First, let me share the file I wrote, and then I'll walk you through all the relevant changes. These files are repo.go
for production and repo_test.go
for test code.
repo.go
package gormdelete import ( "context" "time" "gorm.io/gorm" "gorm.io/gorm/clause" ) type users struct { email string } func delete(ctx context.context, gormdb *gorm.db) error { expirationdate := time.now().utc().add(-(48 * time.hour)) var deletedusers users res := gormdb.withcontext(ctx).table("my_users").clauses(clause.returning{columns: []clause.column{{name: "email"}}}).where("created_at < ?", expirationdate).delete(&deletedusers) if res.error != nil { return res.error } return nil }
Since you didn't provide the complete file, I tried to guess what is missing.
repo_test.go
package gormdelete import ( "context" "database/sql/driver" "testing" "time" "github.com/DATA-DOG/go-sqlmock" "github.com/stretchr/testify/assert" "gorm.io/driver/postgres" "gorm.io/gorm" ) // this is taken directly from the docs // https://github.com/DATA-DOG/go-sqlmock#matching-arguments-like-timetime type AnyTime struct{} // Match satisfies sqlmock.Argument interface func (a AnyTime) Match(v driver.Value) bool { _, ok := v.(time.Time) return ok } func TestDelete(t *testing.T) { db, mock, err := sqlmock.New() if err != nil { t.Fatalf("an error was not expected: %v", err) } conn, _ := db.Conn(context.Background()) gormDb, err := gorm.Open(postgres.New(postgres.Config{ Conn: conn, })) row := sqlmock.NewRows([]string{"email"}).AddRow("<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="9febfaecebdffae7fef2eff3fab1fcf0f2">[email protected]</a>") mock.ExpectBegin() mock.ExpectQuery("DELETE FROM \"my_users\" WHERE created_at < ?").WithArgs(AnyTime{}).WillReturnRows(row) mock.ExpectCommit() err = Delete(context.Background(), gormDb) assert.Nil(t, err) if err = mock.ExpectationsWereMet(); err != nil { t.Errorf("not all expectations were met: %v", err) } }
Here are more changes worth mentioning:
- I instantiated
anytime
according to the documentation (you can see the link in the comments). - I'm second guessing the settings for
db
,mock
andgormdb
, but I think they should be roughly the same. - I switched the usage of
expectexec
toexpectquery
because we will return the results specified by therepo.go
method in theclauses
file set. - You must wrap
expectquery
inexpectbegin
andexpectcommit
. - Finally, note the differences in how drivers expect parameters in sql statements. In production code, you can choose to use
?
or$1
. But in the test code, you can only use?
, otherwise it will not meet expectations.
Hope it can be of some help, otherwise please let me know!
The above is the detailed content of Gorm delete clause sqlmock test. For more information, please follow other related articles on the PHP Chinese website!

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.

You can use the "strings" package in Go to manipulate strings. 1) Use strings.TrimSpace to remove whitespace characters at both ends of the string. 2) Use strings.Split to split the string into slices according to the specified delimiter. 3) Merge string slices into one string through strings.Join. 4) Use strings.Contains to check whether the string contains a specific substring. 5) Use strings.ReplaceAll to perform global replacement. Pay attention to performance and potential pitfalls when using it.

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

ThealternativestoGo'sbytespackageincludethestringspackage,bufiopackage,andcustomstructs.1)Thestringspackagecanbeusedforbytemanipulationbyconvertingbytestostringsandback.2)Thebufiopackageisidealforhandlinglargestreamsofbytedataefficiently.3)Customstru

The"bytes"packageinGoisessentialforefficientlymanipulatingbyteslices,crucialforbinarydata,networkprotocols,andfileI/O.ItoffersfunctionslikeIndexforsearching,Bufferforhandlinglargedatasets,Readerforsimulatingstreamreading,andJoinforefficient

Go'sstringspackageiscrucialforefficientstringmanipulation,offeringtoolslikestrings.Split(),strings.Join(),strings.ReplaceAll(),andstrings.Contains().1)strings.Split()dividesastringintosubstrings;2)strings.Join()combinesslicesintoastring;3)strings.Rep


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

WebStorm Mac version
Useful JavaScript development tools
