【问题标题】:Mocking SQL for unit testing using MockFor in Groovy在 Groovy 中使用 MockFor 模拟 SQL 进行单元测试
【发布时间】:2018-02-21 11:03:02
【问题描述】:

下面的代码 sn-p 是我的 Groovy 类的单元测试用例代码。

在 Eclipse Luna 中使用 maven build 运行此测试用例时出现以下错误:

错误: [错误] com.double.example.application.appMockTest#testUserList MissingMethodException

你们中的任何人都可以对此有所了解吗?如何解决这个问题?

注意:网上讨论很少,但没有任何结果。

public void testUserList() { 
    setup() 
    def userList = [['name':'12345678', 'actual_name':'Paul allan']] 
    List<User> tempList = new ArrayList<User>() 

    mocksql.demand.eachrow { 
        def query, closure -> userList.each(closure) 
    } 

    mocksql.use { 
        apply1 = new apply1(
            <connection string goes here>, 
            <username>, <password>, 
            <schemaname>, 
            "oracle.jdbc.driver.OracleDriver") 
        tempList = apply1.getapply1UserList() 
    } 
} 
} 

【问题讨论】:

  • 完整的堆栈跟踪是否指向特定的行?还有mocksql是什么类的实例?
  • mocksql 是 Sql 类的一个实例,是的,完整的堆栈跟踪指向该行上的特定行 (mocksql.use{})

标签: unit-testing groovy mocking


【解决方案1】:

听起来你的变量 mocksql 应该是 MockFor(Sql),而不是实际的 Sql 对象。

import groovy.sql.Sql
import groovy.mock.interceptor.MockFor

MockFor mocksql = new MockFor(Sql)
mocksql.use { 
    // ...
}

所以这应该很容易解决。

还有一件事:在嘲笑时要非常小心。您正在模拟 eachrow,但 Sql 上没有这样的方法,因为它实际上被称为 eachRow。如果您在测试和真实代码中犯了同样的错误,错误将被隐藏。

在这里,我两次都以相同的方式输入错误的“行”并且我的测试通过了:

import groovy.mock.interceptor.MockFor
import groovy.sql.Sql
import groovy.sql.GroovyRowResult

new MockFor(Sql).with {
    it.demand.withInstance {a,b,c,d, closure -> closure.call( new Sql() ) }
    it.demand.rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrows { query ->
        assert query == 'SELECT * FROM Users'
        return [['name':'12345678', 'actual_name':'Paul allan']]
            .collect { new GroovyRowResult (it) } 
    }
    it.use { assert getUserList() == ['12345678'] }
    it.expect.verify()
}

public String[] getUserList () {
    Sql.withInstance('url', 'user', 'pass', 'driver') { sql ->
        sql.rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrows ('SELECT * FROM Users') 
            .inject (new ArrayList<String>()) { usernames , result -> usernames << result.name }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2023-03-28
    • 2023-03-29
    相关资源
    最近更新 更多