简体   繁体   English

使用go-sqlmock在SQL查询中获取参数值

[英]Get argument value in SQL query with go-sqlmock

I'm currently using go-sqlmock to mock my database. 我当前正在使用go-sqlmock模拟我的数据库。

Is there any way to get the values that have been passed to the sql driver when performing a query?. 执行查询时,是否有任何方法可以获取已传递给sql驱动程序的值? Like the arg variable that is been passing as argument here: 就像在这里作为参数传递的arg变量一样:

import (
   "database/sql"
)

func retrieveInfo(){
    // this function returns an initialized instance of type *sql.DB
    DbDriver := initDb()

    query := "my query"
    arg := 3
    rows, err := Db_driver.Query(query, arg)
    // ...
}

Then I want to test the function, and I would like to know the value of the variable arg while testing. 然后,我想测试该函数,并且想在测试时知道变量arg的值。 I think it should be possible, since it is passed to the "fake" driver that go-sqlmock creates. 我认为应该可行,因为它将传递给go-sqlmock创建的“假”驱动程序。 My test logic looks like this: 我的测试逻辑如下所示:

import "github.com/DATA-DOG/go-sqlmock"

// Inits mock and overwrites the original driver
db, mock, err := sqlmock.New()
Db_driver = db

func TestRetrieveInfo(t *testing.T){
   // query that matchs the one in retrieveInfo()
   query := "..."
   queryRows := sqlmock.NewRows([]string{"column1, column2"}).FromCSVString("value1, value2")
   mock.ExpectQuery(query).WillReturnRows(queryRows)
}

You can wrap the real driver with instrumentation to log the values. 您可以使用工具包装实际的驱动程序以记录值。

Use package github.com/luna-duclos/instrumentedsql . 使用包github.com/luna-duclos/instrumentedsql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对于复合 SQL 查询,在 go-sqlmock 中不会使用 args [] 调用查询 - Call to Query with args [], was not expected in go-sqlmock for compound SQL queries Mocking sql.max() 在 golang 中使用 go-sqlmock - Mocking sql.max() in golang using go-sqlmock 如何为 go-sqlmock 正确设置 Mock Row 和 Query - How to correctly set Mock Row and Query for go-sqlmock Go 单元测试 - 在使用 go-sqlmock 模拟 gorm 时无法将实际 sql 与预期的正则表达式匹配? - Go Unit test - could not match actual sql with expected regexp while mocking gorm using go-sqlmock? mocking gorm `updates` 使用 go-sqlmock 时出现`could not match actual sql` 错误? - `could not match actual sql` error while mocking gorm `updates` using go-sqlmock? 当我的程序中有并发查询时如何使用 go-sqlmock? - How to use go-sqlmock when I have concurrent query in my program? 如何使用带有可变数量参数的 go-sqlmock WithArgs()? - How to use go-sqlmock WithArgs() with a variable number of arguments? 使用 go-sqlmock 创建 gorm 数据库(运行时错误) - Creating a gorm database with go-sqlmock (runtime error) 如何在 go-sqlmock 中添加多个结果集? - How can I add multiple result sets in go-sqlmock? 使用 go-sqlmock 问题测试 gorm 将查询与 mock.ExpectQuery 和 regexp.QuoteMeta 进行比较 - testing gorm with go-sqlmock issue comparing queries with mock.ExpectQuery and regexp.QuoteMeta
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM