2016-10-03 76 views
2

在Grails的3.1.12,我想单元测试服务:Grails的斯波克单元测试要求模拟交易管理

@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 

与失败

,并在试验报告(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注释,测试通过,但是这不是预期的实现。我可以通过嘲笑事务管理器解决问题:

service.transactionManager = Mock(PlatformTransactionManager) { 
    getTransaction(_) >> Mock(TransactionStatus) 
} 

但是,这看起来很尴尬,如果没有错的话。

有没有我忘记调用的一些咒语?

编辑:看起来像an old bug,但它已经关闭了一年多。

回答

5

您是否尝试过评论说修复了问题?如果没有,请尝试使用注释测试类:

@TestMixin(DomainClassUnitTestMixin) 

,然后:试图测试交易服务时

service.transactionManager = getTransactionManager() 
+0

我完全忽略了这一点。这是一个更好的解决方法。谢谢。 – youri

0

居然也得到了同样的错误在Grails的3.3.2。

加入DataTest接口为我解决了这个问题。

class HelloServiceSpec extends Specification implements ServiceUnitTest<HelloService>, DataTest { }