


在PHP开发中,数据库操作是非常常见的需求,而对于一些需要测试的场景,我们又不希望直接操作真实的数据库。这时候,我们可以使用go-sqlmock来模拟数据库查询,从而达到我们想要的测试效果。本文将向大家介绍如何使用go-sqlmock,并将参数插入模拟查询的问题。无论你是PHP开发初学者还是有一定经验的开发者,通过学习本文,你都能够轻松掌握这一技巧,提升你的开发效率。
问题内容
我正在尝试使用 go-sqlmock 模拟我的查询函数并类似地复制数据库表。但是,我没有得到我期望的结果。查询的行为不正常,参数没有插入到查询中并且实际结果不正确。我在这里做错了什么?
这是我正在嘲笑的函数和查询:
func (y *yumdatabase) gettransactionid(pkg string) (int, error) { var id int queryfortid := "select tid from trans_cmdline where cmdline like '%install " + pkg + "%' order by tid desc limit 1" row := y.db.queryrow(queryfortid) switch err := row.scan(&id); err { case sql.errnorows: fmt.println("no rows were returned") return 0, err case nil: return id, nil default: return 0, err } }
这是模拟测试功能:
func testgettransactionid(t *testing.t) { db, mock, err := sqlmock.new() if err != nil { t.fatalf("err not expected: %v", err) } pkg := "tcpdump" rows := sqlmock.newrows([]string{"tid"}).addrow("1").addrow("3") mock.expectquery("select tid from trans_cmdline where cmdline like '%install " + pkg + "%' order by tid desc limit 1").willreturnrows(rows) mockdb := &yumdatabase{ db: db, } got, err := mockdb.gettransactionid("tcpdump") assert.equal(t, 3, got) }
如果上述工作按预期进行,我会在“got”中返回“3”,但我会返回“1”
其次,是否可以将 rows 更改为以下内容:
rows := sqlmock.newrows([]string{"tid", "cmdline"}).addrow("1", "install test").addrow("3", "delete test2")
实际上进行了比较“where cmdline like '%install xyz%'”,因为我尝试了这个,并且收到了以下错误(所有主要代码都构建并工作,包括查询,所以这是一个问题我猜是我写的模拟代码):
error sql: expected 2 destination arguments in Scan, not 1
我希望看到从 sql 查询返回的最高 tid,而不是“addrow”中指定的第一个 tid,并且我希望查询实现对模拟中的“cmdline”行的检查。
解决方法
我就是这样管理你的需求的。首先,让我分享代码,然后,我将引导您完成所有相关更改。该代码包含在两个文件中:repo.go
和 repo_test.go
。
repo.go
文件
package repo import ( "database/sql" "fmt" ) func gettransactionid(db *sql.db, pkg string) (int, error) { var id int row := db.queryrow("select tid from trans_cmdline where cmdline like '%install $1%' order by tid desc limit 1", pkg) switch err := row.scan(&id); err { case sql.errnorows: fmt.println("no rows were returned") return 0, err case nil: return id, nil default: return 0, err } }
这里有两个小改进:
-
*sql.db
作为参数传入。正如最佳实践所建议的,函数是一等公民。这就是为什么我更愿意尽可能坚持使用它们。 - 我使用准备好的语句来传递查询的参数。不是简单的字符串连接。因此,可以更轻松地拦截传递给查询的参数并对其设置期望
现在让我们切换到测试代码。
repo_test.go
文件
package repo import ( "database/sql" "testing" "github.com/DATA-DOG/go-sqlmock" "github.com/stretchr/testify/assert" ) func TestGetTransactionId(t *testing.T) { db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { t.Fatalf("err not expected while opening mock db, %v", err) } t.Run("HappyPath", func(t *testing.T) { rows := sqlmock.NewRows([]string{"tid"}).AddRow("1") mock.ExpectQuery("SELECT tid FROM trans_cmdline WHERE cmdline LIKE '%install $1%' ORDER BY tid DESC LIMIT 1"). WithArgs("tcpdump"). WillReturnRows(rows) got, err := GetTransactionId(db, "tcpdump") assert.Equal(t, 1, got) assert.Nil(t, err) }) t.Run("NoRowsReturned", func(t *testing.T) { mock.ExpectQuery("SELECT tid FROM trans_cmdline WHERE cmdline LIKE '%install $1%' ORDER BY tid DESC LIMIT 1"). WithArgs("tcpdump"). WillReturnError(sql.ErrNoRows) got, err := GetTransactionId(db, "tcpdump") assert.Equal(t, 0, got) assert.Equal(t, sql.ErrNoRows, err) }) }
这里,您需要注意更多更改:
- 在实例化
db
和mock
时,您应该将sqlmock.querymatcherequal
作为参数传递给。因此,它将完全匹配查询。 -
expectquery
方法现在使用准备好的语句功能并需要一个参数(例如本例中的tcpdump
)。 - 重构了断言以利用
github.com/stretchr/testify/assert
包。
我希望这可以帮助您解决问题,请告诉我!
The above is the detailed content of Issues using go-sqlmock and inserting parameters into simulated queries. For more information, please follow other related articles on the PHP Chinese website!

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

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