使用SQL和dataSource测试服务

时间:2012-03-30 16:14:59

标签: grails

我有一个使用Groovy SQL对数据库进行一些sql调用的服务。我对此服务的测试失败,因为dataSource为null。如何让dataSource成为单元测试中的适当连接?

ExampleService.groovy

class ExampleService { 
    def dataSource 

    def getSQL() { 
        def sql = new Sql(dataSource) 
        def query = "some query" 
        sql.call(query) 
        sql.close() 
    } 
} 

ExampleServiceTests.groovy

@TestFor(ExampleService) 
class ExampleServiceTests { 
    void testExample() { 
        def es = new ExampleService() 
        es.getSQL() 
    } 
} 

在上面的示例中,我收到以下错误:

java.lang.NullPointerException: Must specify a non-null Connection

1 个答案:

答案 0 :(得分:5)

单元测试中没有数据库,仅在集成测试中。单元测试中的所有内容都使用模拟,因为没有活动的Spring,Hibernate,数据库,插件等。持久性应始终针对数据库进行测试,即使它只是内存中的HSQL或H2数据库,也不是MySQL的开发版本Postgres的/甲骨文/等。数据库中。