功能测试 Grails/Geb:域 class 在第二次调用后可用

Functional Test Grails/Geb: Domain class is available after second call

我在 Grails 3 中尝试了新的功能测试。它测试一个简单的 REST API,创建一个 POST 请求,然后观察是否创建了新资源。

import geb.spock.GebSpec
import grails.converters.JSON
import grails.test.mixin.integration.Integration
import grails.transaction.Rollback
import groovy.util.logging.Slf4j
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity

@Integration
@Rollback
@Slf4j
class QuestionFunctionalSpec extends GebSpec {
    void "POST  to /questions creates new question"() {
        setup:
        log.debug("Existing questions: ${Question.list().collect { [id: it.id, text: it.text] }}")
        def jsonRequest = [text: "How to cook for people?"] as JSON

        when: "The api call is made"
        def httpPost = new HttpPost("localhost:8080/api/v1/questions")
        httpPost.setEntity(new StringEntity(jsonRequest.toString()));
        HttpClients.createDefault().execute(httpPost)

        then: "New question was created"
        //log.debug("Questions after test (first domain class call): ${Question.list().collect { [id: it.id, text: it.text] }}")
        //log.debug("Questions after test (second domain class call): ${Question.list().collect { [id: it.id, text: it.text] }}")
        assert Question.list().size() == 1
    }
}

本地一切正常,但 运行 这在我的 CI 服务器上,我的测试失败了。取消注释第一个 log.debug() 我收到一条消息,指出数据库中没有问题资源,但是测试没有失败。取消对第二个 log.debug() 的注释,我看到问题资源实际上存在,但它仅在第二个域 class 调用中可用。

我是不是漏掉了什么。我怀疑 Apache HttpClient 不是同步的,但实际上是同步的。你有类似的经历吗? Geb 有同步问题吗?

谢谢, 马特奥

我发现不应在功能测试中直接访问 GORM,因为测试本身可能 运行 在单独的 JVM (invoking GORM methods from Geb tests) 中。

适当的方法是使用远程控制插件 (https://grails.org/plugin/remote-control). However, it doesn't have support for Grails 3 yet (https://github.com/alkemist/grails-remote-control/issues/27)。