Pergunta

I have a service method that locks a database row.

public String getNextPath() {
    PathSeed.withTransaction { txn ->
        def seed = PathSeed.lock(1)
        def seedValue = seed.seed
        seed.seed++
        seed.save()
    }

}

This is how my spock test looks like:

void "getNextPath should return a String"() {
    when:
        def path = pathGeneratorService.getNextPath()

    then:
        path instanceof String
}

It's just a simple initial test. However I get this error when I run the test:

java.lang.UnsupportedOperationException: Datastore [org.grails.datastore.mapping.simple.SimpleMapSession] does not support locking.
at org.grails.datastore.mapping.core.AbstractSession.lock(AbstractSession.java:603)
at org.grails.datastore.gorm.GormStaticApi.lock_closure14(GormStaticApi.groovy:343)
at org.grails.datastore.mapping.core.DatastoreUtils.execute(DatastoreUtils.java:302)
at org.grails.datastore.gorm.AbstractDatastoreApi.execute(AbstractDatastoreApi.groovy:37)
at org.grails.datastore.gorm.GormStaticApi.lock(GormStaticApi.groovy:342)
at com.synacy.PathGeneratorService.getNextPath_closure1(PathGeneratorService.groovy:10)
at org.grails.datastore.gorm.GormStaticApi.withTransaction(GormStaticApi.groovy:712)
at com.synacy.PathGeneratorService$$EOapl2Cm.getNextPath(PathGeneratorService.groovy:9)
at com.synacy.PathGeneratorServiceSpec.getNextPath should return a String(PathGeneratorServiceSpec.groovy:17)

Does anyone have any idea what this is?

Foi útil?

Solução

The simple GORM implementation for Unit tests does not support some features, such as locking. Moving your test to an integration test will use the full implementation of GORM instead of the simple implementation used by unit tests.

Typically when you find yourself using anything more than the very basic features of GORM you will need to use integration tests.

Updated 10/06/2014

In more recent versions of Grails and GORM there is now the HibernateTestMixin which allows you to test/use such features in Unit tests. Further information can be found in the documentation.

Outras dicas

As a workaround, I was able to get it working by using Groovy metaprogramming. Applied to your example:

def setup() { // Current spec does not test the locking feature, // so for this test have lock call the get method // instead. PathSeed.metaClass.static.lock = PathSeed.&get }

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top