简体   繁体   中英

Spock tests failing after grails upgrade 2.2 -> 2.3.7

I have a command object with a couple of static methods which access other domain objects.

static def isAValidSerial(String serialReference) {
   return InventoryMaster.partSerialReferenceList(null, serialReference).size() > 0
}

This method is called by the validation constraints on the command object.

In a unit test I mock this behavior.

TransactionDetailCommand.metaClass.static.isAValidSerial = { String a -> println "mocked method called"; true }

before invoking some validation:

obj.validate(['serialReference'])

However this is throwing an exception where it didn't with 2.2.0.

The error is:

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

Despite the mocking when it's called from the validator it appears to be trying to invoke the real method and not the mock. If I put an explicit println before the obj.validate() it correctly prints the test text from the mocked method and returns the mocked value. This worked on 2.2 but now fails. I didn't used the grails update command. I created a new project and copied stuff to it. I've found various tips including removing the forked JVM stuff from the build config but nothing seems to work.

Anyone any ideas? Thanks.

I finally managed to get this working. Firstly I had to explicitly declare the collaborating class (InventoryMaster) within the @Mock annotation - on 2.2.n this wasn't required. Also when invoking mocked static methods from my validator I had to explicitly qualify the static call .. So what used to look like

if (!(cmdObj.transactionType.transactionIsAReceipt() || isAValidSerial(serialReference))) {
                return 'TransactionDetailCommand.serialReference.not.found'
}

and work under 2.2.n had to be converted to ..

if (!(cmdObj.transactionType.transactionIsAReceipt() || TransactionDetailCommand.isAValidSerial(serialReference))) {
                return 'TransactionDetailCommand.serialReference.not.found'
            }

which kinda makes sense as I previously mocked the isAValidSerial using

TransactionDetailCommand.metaClass.static.isAValidSerial = {a -> println "running mock isAValidSerial -> true"; true }

Maybe that was 2.2.n being lax .. Anyway, my tests now work again !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM