groovy - Grails integration testing NPE using h2 -


i trying write integration test in grails using h2 database. i'm using h2 don't have setup database in ci server. i'm having problems initializing data in database.

this test looks right now:

class pathgeneratorservicespec extends specification {    def pathgeneratorservice    def setup() {     pathseed pathseed = new pathseed(id:1, seed:0).save()   }    void "getnextpath should return string"() {     when:       def retval = pathgeneratorservice.getnextpath()      then:       retval instanceof string   } } 

however when try run test i'm getting npe: cannot property 'seed' on null object

this service looks way:

public string getnextpath() {     def seedvalue = getnextseed()     def path = createpath(seedvalue)     return path }  private def getnextseed() {     def seedvalue     pathseed.withtransaction { txn ->         def seed = pathseed.lock(1)         seedvalue = seed.seed         seed.seed++         seed.save()     }     return seedvalue } 

i think problem caused attempt assign value identity column. if replace this:

pathseed pathseed = new pathseed(id:1, seed:0).save() 

with

pathseed pathseed = new pathseed(seed:0).save() 

and replace:

pathseed.lock(1) 

with:

pathseed.first() 

does solve problem? should never need explicitly assign value id, , should avoid hardcoding id values, e.g. pathseed.lock(1)

update

you asked in comment

is there way lock database using first?

no, can adapt solution above use pessimistic locking so:

class pathgeneratorservicespec extends specification {    def pathgeneratorservice   private long pathseedid    def setup() {     pathseedid = new pathseed(seed:0).save().id   }    void "getnextpath should return string"() {     when:       def retval = pathgeneratorservice.getnextpath(pathseedid)      then:       retval instanceof string   } }  public string getnextpath(id) {     def seedvalue = getnextseed(id)     def path = createpath(seedvalue)     return path }  private def getnextseed(id) {     def seedvalue     pathseed.withtransaction { txn ->         def seed = pathseed.lock(id)         seedvalue = seed.seed         seed.seed++         seed.save()     }     return seedvalue } 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -