简体   繁体   中英

How can I test my Grails service save method?

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\u003c/code> 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)

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.

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