【问题标题】:How I create a Sql mock unit test Grails我如何创建 Sql 模拟单元测试 Grails
【发布时间】:2018-02-02 19:21:48
【问题描述】:

我正在尝试对 Grails 进行单元测试,我尝试过的内容如下:

def getMarca(CrDocumento crDocumento) {
    if (!crDocumento) {
        return null
    }
    String sql = ""

    sql = "select marca.id as marca_id from cr_documento, matricula, cr_renegoc_boleto, oferta_polo_turma, oferta_polo, oferta, marca where cr_documento.id = cr_renegoc_boleto.cr_documento_id and cr_documento.matricula_id = matricula.id and matricula.oferta_polo_turma_id = oferta_polo_turma.id and oferta_polo_turma.oferta_polo_id = oferta_polo.id and oferta_polo.oferta_id = oferta.id and oferta.marca_id = marca.id and cr_documento.id = $crDocumento.id"

    def sqlGroovy = new Sql(dataSource)
    def marcaId = sqlGroovy.firstRow(sql)?.marca_id
    return Marca.findById(marcaId)
}

但我无法模拟 Sql 类并看到此错误:

groovy.lang.GroovyRuntimeException:方法 groovy.sql.Sql# 的方法重载不明确。

由于以下之间的原型重叠,无法解析为 [null] 调用哪个方法: [接口 java.sql.Connection]
[接口javax.sql.DataSource]

【问题讨论】:

  • 你的测试是什么样的?您收到异常是因为 dataSource 为 null 并且 groovy 不知道您尝试调用哪个 Sql 构造函数,因为有 2 个采用单个参数
  • 我注意到,dataSource 为空,但我如何模拟它?
  • 查询中的所有其他表是否也是 Grails 域对象?你可能不需要像这样使用dataSource,看看这个查询数据库的各种方法tatiyants.com/how-and-when-to-use-various-gorm-querying-options

标签: sql unit-testing testing grails


【解决方案1】:

查询 id 的代码应该在一个单独的服务中,然后您可以模拟。

【讨论】:

    【解决方案2】:

    来自Forum

    服务/数据源定义必须发生在方法之外。 然后 Spring 将注入 bean。

    试试这样的:

    FooController { 
            def dataSource_mydb 
    
            def barAction() { 
                    def sql = new Sql(dataSource_mydb) 
            } 
    } 
    

    【讨论】:

    • 好的,但你能告诉我如何测试这个控制器吗?
    猜你喜欢
    • 2015-01-11
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    • 2012-11-25
    相关资源
    最近更新 更多