2014-12-24 7 views
0

Я реализую плагин там, где есть служба.Записать интеграционный тестовый пример для плагинов Grails

class PersonalEquipmentRateService { 

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

} 

У меня есть тестовые записи для домена, работающих fine.But в то время как я пишу тесты для служб Я получаю следующее сообщение об ошибке.

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 = "целевой/классы"

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

Причина заключается в том, что у вас нет какой-либо базы данных постоянный двигатель, т.е. либо спящий режим, либо 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 версия & в некоторых средах, как JDK версии и т.д.

Спасибо,
SA

+0

Я использую h2 базы данных. –

+0

Хорошо, Какую версию грааля вы используете для плагина? –

+0

Это grails 2.3.9 –

Смежные вопросы