Grails Spock单元测试需要模拟事务管理器 [英] Grails Spock unit test requires to mock transaction manager
问题描述
在Grails 3.1.12中,我要对服务进行单元测试:
In Grails 3.1.12, I want to unit test a service:
@Transactional
class PlanService {
List<Plan> getPlans(Map params) {
def currentUser = (User)springSecurityService.getCurrentUser()
return Plan.findAllByCompany(currentUser.employer, params)
}
}
喜欢这个:
@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
}
从控制台运行测试:
grails> test-app my.PlanServiceSpec -unit
失败:
my.FundingPlanServiceSpec > Retrieve plan from the current user FAILED
java.lang.IllegalStateException at PlanServiceSpec.groovy:48
并在测试报告(HTML)中:
and in the test report (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.
现在,如果我注释掉服务中的@Transactional
批注,则测试会通过,但这不是预期的实现.我可以通过模拟事务管理器来解决此问题:
Now if I comment out the @Transactional
annotation in the service, the test passes, but that's not the intended implementation. I am able to work around the problem by mocking the transaction manager:
service.transactionManager = Mock(PlatformTransactionManager) {
getTransaction(_) >> Mock(TransactionStatus)
}
但这似乎很尴尬,即使没有错.
But this seems very awkward, if not wrong.
我忘了援引一些咒语吗?
Is there some incantation I forgot to invoke?
类似于一个老错误,但是已经关闭了一年多.
looks similar to an old bug, but it's been closed more than a year.
推荐答案
您是否尝试过注释说的解决问题的内容?如果没有,请尝试使用以下方法注释测试类:
Have you tried what a comments says that fixes the problem? If not, try to annotate the test class with:
@TestMixin(DomainClassUnitTestMixin)
然后:
service.transactionManager = getTransactionManager()
这篇关于Grails Spock单元测试需要模拟事务管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!