Using Grails 2.0.0 I am created service, that creates instances of Player class and saves it at database. Then I’m wrote JUnit integration test that check that service method createNewPlayer(String platformID) throws exception if constraint validation failed at Player.save(failOnError : true).
All goes fine, but after method shouldFail(…) if I’m calls:
assert Player.list().size() == 1;
I am get this error:
--Output from testCreatingNewPlayerWithExistingID--
| Error 2012-02-15 21:52:05,293 [main] ERROR hibernate.AssertionFailure - an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)
Message: null id in test1.Player entry (don't flush the Session after an exception occurs)
My question is: how to test throwing exceptions within shouldFail method so that Hibernate is not kept in memory invalid instances of Player classes with null ids after this?
Below my code examples:
class WorkingService
{
Player createNewPlayer(String platformID) throws ValidationException {
Player player = new Player(platformID: platformID);
return player.save(failOnError : true);
}
}
class Player
{
String platformID
static constraints = {
platformID nullable: false, blank: false, unique: true
}
}
@TestFor(WorkingService)
class WorkingServiceTests
{
WorkingService workingService;
void testCreatingNewPlayerWithExistingID()
{
def player = new Player(platformID: "1");
player.save(flush: true);
assert Player.list().size() == 1;
shouldFail ValidationException, {
player = workingService.createNewPlayer("1");
}
assert Player.list().size() == 1;
}
}
I think the problem is that you’re mixing integration tests and unit tests. An integration test should extend GroovyTestCase and not use AST transform annotations like
TestFor. This passes in my test app:Unrelated – you shouldn’t use
list().size()to get the count from the database since that loads every instance just to get the number; usecount()instead. Alsonullable: falseis the default so it’s redundant to specify it.