Reputation: 3722
I've created Grails service using grails create-service TaskCRUDService
. That command created files TaskCRUDService.groovy
in grails-app\services
and TaskCRUDServiceSpec.groovy
in test\unit
folder.
The only method in my TaskCRUDService
is
Task save(String name) {
Task task = new Task()
task.name = name
task.save(flush: true, failOnError: true)
}
I wanted to test this method so, I've filled the body of "test something" method generated by the Grails in the test class. So this is my TaskCRUDServiceSpec
code:
@TestFor(TaskCRUDService)
class TaskCRUDServiceSpec extends Specification {
void "test something"() {
when:
Task t = service.save('task name')
then:
assert t.name == 'task name'
}
}
But the test doesn't work. When I run grails test-app
I get
java.lang.IllegalStateException: Method on class [Task] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.
at TaskCRUDService.$tt__save(TaskCRUDService.groovy:29)
at TaskCRUDServiceSpec.test create(TaskCRUDServiceSpec.groovy:24)
Upvotes: 0
Views: 773
Reputation: 75671
That looks like it should work, but even if it did, it's a bad test. Never use unit tests for testing persistence. Use an integration test so you're using a real database and not just the in-memory GORM implementation that uses a ConcurrentHashMap to store the data.
Upvotes: 4