在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,但它已經關閉了一年多。
我完全忽略了這一點。這是一個更好的解決方法。謝謝。 – youri