简体   繁体   中英

Mocking SQL for unit testing using MockFor in Groovy

Below code snippet is my unit test case code for Groovy class.

While running this test case in Eclipse Luna using maven build getting below error:

Errors: [ERROR] 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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