简体   繁体   English

在 Groovy 中使用 MockFor 进行单元测试的模拟 SQL

[英]Mocking SQL for unit testing using MockFor in Groovy

Below code snippet is my unit test case code for Groovy class.下面的代码片段是我的 Groovy 类的单元测试用例代码。

While running this test case in Eclipse Luna using maven build getting below error:在 Eclipse Luna 中使用 maven build 运行此测试用例时出现以下错误:

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

Any one of you could please throw some light on this?你们中的任何人都可以对此有所了解吗? How to fix this issue?如何解决这个问题?

Note: saw few online discussions but nothing worked out.注意:在网上看到的讨论很少,但没有任何结果。

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() 
    } 
} 
} 

It sounds like your variable mocksql should be a MockFor(Sql), not an actual Sql object.听起来您的变量 mocksql 应该是 MockFor(Sql),而不是实际的 Sql 对象。

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

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

So that should be an easy fix.所以这应该很容易解决。

One more thing: just be really careful with your mocking.还有一件事:要非常小心你的嘲笑。 You are mocking eachrow, but there is no such method on Sql, since it's actually called eachRow.您正在嘲笑eachrow,但Sql 上没有这样的方法,因为它实际上被称为eachRow。 If you make the same mistake in your test and your real code, the error will be hidden.如果您在测试和实际代码中犯同样的错误,错误将被隐藏。

Here I've mistyped "rows" in the same way both times and my test passes:在这里,我两次都以相同的方式错误输入了“行”,并且我的测试通过了:

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 }
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM