Grails Spock单元测试需要模拟事务管理器

you*_*uri 5 service grails unit-testing mocking spock

在Grails 3.1.12中,我想对服务进行单元测试:

@Transactional
class PlanService {
    List<Plan> getPlans(Map params) {
        def currentUser = (User)springSecurityService.getCurrentUser()
        return Plan.findAllByCompany(currentUser.employer, params)
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样:

@TestFor(PlanService)
@Mock([Plan, User, Company])
class PlanServiceSpec extends Specification {
    void "Retrieve plan from the current user"() {
        setup:
        // create and save entities here

        when: "the plans are retrieved"
        def params = null
        def plans = service.getPlans(params)

        then: "the result should only include plans associated to the current user's company"
        plans.size() == 2
}
Run Code Online (Sandbox Code Playgroud)

从控制台运行测试:

grails> test-app my.PlanServiceSpec -unit
Run Code Online (Sandbox Code Playgroud)

失败:

my.FundingPlanServiceSpec > Retrieve plan from the current user FAILED
java.lang.IllegalStateException at PlanServiceSpec.groovy:48
Run Code Online (Sandbox Code Playgroud)

并在测试报告(HTML)中:

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.
Run Code Online (Sandbox Code Playgroud)

现在,如果我@Transactional在服务中注释掉注释,则测试通过,但这不是预期的实现.我可以通过模拟事务管理器来解决这个问题:

service.transactionManager = Mock(PlatformTransactionManager) {
    getTransaction(_) >> Mock(TransactionStatus)
}
Run Code Online (Sandbox Code Playgroud)

但这似乎很尴尬,如果不是错的话.

我忘了援引一些咒语吗?

编辑:看起来类似于一个旧的错误,但它已关闭超过一年.

Fra*_*cía 8

您是否尝试过注释解决问题的方法?如果没有,请尝试使用以下命令注释测试类:

@TestMixin(DomainClassUnitTestMixin)
Run Code Online (Sandbox Code Playgroud)

然后:

service.transactionManager = getTransactionManager()
Run Code Online (Sandbox Code Playgroud)