使用SQL和dataSource的测试服务 [英] Testing Service with SQL and dataSource

查看:164
本文介绍了使用SQL和dataSource的测试服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Groovy SQL对数据库进行一些sql调用的服务.我的这项服务测试失败,因为dataSource为null.如何获得dataSource作为单元测试中的适当连接?

I have a service that uses Groovy SQL to make some sql calls to the database. My tests for this service are failing because dataSource is null. How do I get dataSource to be the appropriate connection inside a unit test?

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

在上面的示例中,出现以下错误:

In the above example I get the following error:

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

推荐答案

在单元测试中没有数据库,只有在集成测试中.由于没有活动的Spring,Hibernate,数据库,插件等,因此单元测试中的所有内容都使用了模拟功能.应始终针对数据库测试持久性,即使它只是内存中的HSQL或H2数据库,或者是MySQL/的开发版本Postgres/Oracle/等数据库.

There's no database in unit tests, only in integration tests. Everything in unit tests uses mocking since there's no active Spring, Hibernate, database, plugins, etc. Persistence should always be tested against a database, even if it's just the in-memory HSQL or H2 database, or a dev version of a MySQL/Postgres/Oracle/etc. database.

这篇关于使用SQL和dataSource的测试服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆