为grails插件编写集成测试用例

时间:2014-12-24 08:39:15

标签: grails testing integration-testing grails-plugin spock

我正在实施一个插件,我有服务。

class PersonalEquipmentRateService {

    List<PersonalEquipmentRate> findActiveByDate(Date date){
        List<PersonalEquipmentRate> personalEquipmentRateList = PersonalEquipmentRate.createCriteria().list {
            and {
                ge 'effectiveDate', date
                le 'expiryDate', date
            }
        }
        return personalEquipmentRateList
    }

}

我已经为那些工作正常的域编写了测试用例。但是当我为服务编写测试用例时,我遇到了错误。

java.lang.IllegalStateException: Method on class [PersonalEquipment] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.

我的测试用例代码是: -

class PersonalEquipmentRateServiceSpec extends IntegrationSpec {

    def personalEquipmentRateService

    def setup() {
    }

    def cleanup() {
    }

    void "test personalEquipmentRateService"() {
        when:
        PersonalEquipment personalEquipment= new PersonalEquipment(ownerId:1,assetId:1,unitNumber:"UNO",hourlyRate:1,dailyRate:100,dayRateHours:12,businessUnitId:12,personalEquipmentRate:null,dateCreated:new Date(),lastUpdated:new Date(),siteId:12)
        personalEquipment.save(failOnError: true,flush:true)
        PersonalEquipmentRate personalEquipmentRate=new PersonalEquipmentRate(rate:100.0,effectiveDate:getDate('06/05/2014'),expiryDate:getDate('16/12/2014'),dateCreated:new Date(),lastUpdated:new Date(),personalEquipment:personalEquipment,uomId:1)
        personalEquipmentRate.save(failOnError: true,flush:true)
        List<PersonalEquipmentRate> personalEquipmentRateList=personalEquipmentRateService.findActiveByDate(getDate('06/05/2014'))

        then:
        assert true
        1==personalEquipmentRateList.size()

    }
    private Date getDate(String dateString) {
        return new Date().parse("d/M/yyyy", dateString)
    }

}

建议我解决一些问题。

我的Build.config grails.project.class.dir =&#34; target / classes&#34;

grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"

grails.project.fork = [
    // configure settings for compilation JVM, note that if you alter the Groovy version forked compilation is required
    //  compile: [maxMemory: 256, minMemory: 64, debug: false, maxPerm: 256, daemon:true],

    // configure settings for the test-app JVM, uses the daemon by default
    test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
    // configure settings for the run-app JVM
    run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
    // configure settings for the run-war JVM
    war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
    // configure settings for the Console UI JVM
    console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]
]

grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution = {
    // inherit Grails' default dependencies
    inherits("global") {
        // uncomment to disable ehcache
        // excludes 'ehcache'
    }
    log "warn" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    repositories {
        grailsCentral()
        mavenLocal()
        mavenCentral()
        // uncomment the below to enable remote dependency resolution
        // from public Maven repositories
        //mavenRepo "http://repository.codehaus.org"
        //mavenRepo "http://download.java.net/maven/2/"
        //mavenRepo "http://repository.jboss.com/maven2/"
    }
    dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
        // runtime 'mysql:mysql-connector-java:5.1.27'
    }

    plugins {
        build(":release:3.0.1",
              ":rest-client-builder:1.0.3") {
            export = false
        }
        compile (":hibernate:3.6.10.18")
    }
}

DataSource.config

dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "org.h2.Driver"
    username = "sa"
    password = ""
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
//    cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
    singleSession = true // configure OSIV singleSession mode
}

// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', ''
            url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
            properties {
               // See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
               jmxEnabled = true
               initialSize = 5
               maxActive = 50
               minIdle = 5
               maxIdle = 25
               maxWait = 10000
               maxAge = 10 * 60000
               timeBetweenEvictionRunsMillis = 5000
               minEvictableIdleTimeMillis = 60000
               validationQuery = "SELECT 1"
               validationQueryTimeout = 3
               validationInterval = 15000
               testOnBorrow = true
               testWhileIdle = true
               testOnReturn = false
               jdbcInterceptors = "ConnectionState"
               defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

原因是你没有任何数据库持久性引擎,即hibernate或mongodb。确保你的插件的BuildConfig.groovy上安装了休眠。

plugins {
    build(":release:3.0.1",
          ":rest-client-builder:1.0.3") {
        export = false
    }
    runtime ':hibernate:3.6.10.13'
    // Other dependencies
}

一般情况下,每当您提出任何问题时,请指明您的Grails版本&amp;一些环境,如jdk版等。

谢谢,
SA