Отсутствие ошибки transactionManager в тесте интеграции Grails 3

Я создал новый угловой проект Grails 3.1.4 вместе с несколькими объектами домена и контроллерами, расширяющими RestfulController. Ниже я создал интеграционный тест. Когда я запускаю grails test-app -integration, я получаю сообщение об ошибке

java.lang.IllegalStateException: No transactionManager was specified. Using @Transactional or @Rollback requires a valid configured transaction manager. If you are running in a unit test ensure the test has been properly configured and that you run the test suite not an individual test method.
    at grails.transaction.GrailsTransactionTemplate.<init>(GrailsTransactionTemplate.groovy:60)
    at com.waldoware.invoicer.BillingEntityRestControllerIntegrationSpec.$tt__$spock_feature_0_0(BillingEntityRestControllerIntegrationSpec.groovy:29)
    at com.waldoware.invoicer.BillingEntityRestControllerIntegrationSpec.test all entities_closure2(BillingEntityRestControllerIntegrationSpec.groovy)
    at groovy.lang.Closure.call(Closure.java:426)
    at groovy.lang.Closure.call(Closure.java:442)
    at grails.transaction.GrailsTransactionTemplate$1.doInTransaction(GrailsTransactionTemplate.groovy:70)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
    at grails.transaction.GrailsTransactionTemplate.executeAndRollback(GrailsTransactionTemplate.groovy:67)
    at com.waldoware.invoicer.BillingEntityRestControllerIntegrationSpec.test all entities(BillingEntityRestControllerIntegrationSpec.groovy)

Тестовый класс:

package com.waldoware.invoicer

import grails.test.mixin.integration.Integration
import grails.transaction.*
import spock.lang.*

@Integration
@Rollback
class BillingEntityRestControllerIntegrationSpec extends Specification {

    def setupData() {
        def biller = new BillingEntity()
        biller.with {
            companyName = "Acme, Inc."
        }
        def ledger = new Ledger(name: "My Ledger", billingEntity: biller).save(failOnError: true, flush: true)
    }

    void 'test all entities'() {
        when:
        setupData()
        new BillingEntityRestController().index()

        then:
        response.contentType == 'application/json;charset=UTF-8'
        response.status == HttpServletResponse.SC_OK
        response.text == "[{}]"
    }
}

У меня есть источник данных, настроенный в application.yml:

environments:
    development:
        dataSource:
            dbCreate: none
            url: jdbc:h2:./devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    test:
        dataSource:
            dbCreate: update
            url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    production:
        dataSource:
            dbCreate: update
            url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
            properties:
                jmxEnabled: true
                initialSize: 5
                maxActive: 50
                minIdle: 5
                maxIdle: 25
                maxWait: 10000
                maxAge: 600000
                timeBetweenEvictionRunsMillis: 5000
                minEvictableIdleTimeMillis: 60000
                validationQuery: SELECT 1
                validationQueryTimeout: 3
                validationInterval: 15000
                testOnBorrow: true
                testWhileIdle: true
                testOnReturn: false
                jdbcInterceptors: ConnectionState
                defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED

person Paul Waldo    schedule 30.03.2016    source источник
comment
Единственная причина, по которой мне нужен интеграционный тест, заключается в том, что у меня есть собственный JSON Marshaller, который не вызывается в модульном тесте.   -  person Paul Waldo    schedule 15.04.2016
comment
Вы когда-нибудь понимали это? Я переношу приложение Grails 2 и вижу ту же проблему с некоторыми из наших интеграционных тестов.   -  person Rado    schedule 07.10.2016
comment
@rado Я только что удалил пользовательские маршалеры в пользу gson. Это путь Grails 3 :-)   -  person Paul Waldo    schedule 08.10.2016


Ответы (2)


Это может помочь, если в вашем build.gradle не настроен подключаемый модуль сохраняемости, который настраивает менеджер транзакций (примеры включают hibernate4, mongodb, neo4j и т. д., или у вас не настроен dataSource в grails-app/conf/application.yml.

Если это так, просто удалите аннотацию @Rollback, и это должно решить проблему.

person Graeme Rocher    schedule 31.03.2016
comment
Я хотел бы сохранить @Rollback, чтобы тестовый прогон не загрязнял базу данных для других тестов. Я пытался удалить откат, но при запуске теста получил эту ошибку: org.springframework.dao.DataAccessResourceFailureException: Could not obtain current Hibernate Session; nested exception is org.hibernate.HibernateException: No Session found for current thread - person Paul Waldo; 01.04.2016

Наткнулся на это при устранении неполадок в моем собственном интеграционном тесте. Я решил свою проблему, удалив каталог out.

delete project-folder/out/

Теперь вам также нужно очистить и перестроить файл войны. Это должно выполнить несколько дополнительных шагов в процессе сборки и решить некоторые проблемы.

./grailsw clean
./grailsw war

Теперь, когда вы запускаете свои тесты, вы не должны видеть сообщение об ошибке.

person Jason Heithoff    schedule 29.06.2018