Testing after logging into Grails
I just have the following scenario:
class OwnedRights {
static belongsTo = [comp: Competition]
@Transactional
def afterInsert() {
// Erroring out here.
Event.findAllByComp(comp).each { event ->
// Do something with event.
}
}
}
When I try to store something like the following in my unit test:
def ownedRights = new OwnedRights(params).save(flush: true, failOnError: true)
I see the following stack:
java.lang.NullPointerException at org.springframework.transaction.support.TransactionTemplate.execute (TransactionTemplate.java:130) at org.codehaus.groovy.grails.orm.support.GrailsTransactionTemplate.execute (GrailsTransactionTemplate.g.) springframework.util.ReflectionUtils.invokeMethod (ReflectionUtils.java:209) at org.springframework.util.ReflectionUtils.invokeMethod (ReflectionUtils.java:194)
This led me to this Jira issue which indicated that I was not using annotation @Mock
, however in my test I mocked all the domain classes in use:
@Mock([OwnedRights, Sport, Competition, Event])
Is this a known issue with Hibernate events containing GORM logic?
Attempts to solve
I tried to override the methods afterInsert()
and beforeDelete
using metaClass:
OwnedRights.metaClass.afterInsert = null;
OwnedRights.metaClass.beforeDelete = null;
and
OwnedRights.metaClass.afterInsert = {};
OwnedRights.metaClass.beforeDelete = {};
Both of these did not affect the result. If I comment out the afterInsert event, the save works fine.
source to share
You mention @Mock. This can only be used in unit tests, but then you should never try to validate transactions in unit tests.
This is no-no. Testing transactions in the integration test. The work they've done of letting you have an in-memory implementation of GORM built in is great, but transactions are a feature of the database. You simply cannot expect an in-memory implementation (supported by Map!) To behave like a database. The ones you are testing are the behavior of the unit test implementation of GORM, not the actual database. Thus, the test is useless in the real world.
source to share