![](/img/trans.png)
[英]Target specific package when running Grails integration tests using Gradle
[英]Grails dynamic methods not present when running integration tests
我正在使用Grails 2.5.4開發項目,目前正在嘗試運行一些未運行的集成測試。 我已經調試了該問題,發現在集成測試中運行時顯然沒有要測試的服務上的某些動態方法(如果在應用程序的上下文中運行該方法,則所有方法都可以使用)。 在我嘗試運行的許多測試中都會發生這種情況,我選擇了其中的一個作為示例,但其他未通過的測試則存在相同的問題。
我有這個領域課程
class Event {
...
static hasMany = [
bundles : Bundle
]
...
}
以及要測試的服務方法:
@Transactional
class BundleService {
...
void assignEvent(Event event, List bundleIds) {
..
for (id in bundleIds) {
event.addToBundles(Bundle.get(id))
}
}
...
}
所以我運行了這個spock測試
class BundleServiceIntegrationSpec extends Specification {
BundleService bundleService
EventService eventService
private BundleTestHelper bundleHelper = new BundleTestHelper()
...
void '04. Test deleteBundleAndAssets method'() {
when: 'a new Bundle is created'
Bundle bundle = bundleHelper.createBundle(project, 'Test Bundle')
and: 'a new Event is created'
Event event = eventService.create(project, 'Test Event')
and: 'the above Bundle is assigned to the Event'
bundleService.assignEvent(event, [bundle.id])
...
}
它在BundleService的moveEvent.addToBundles(Bundle.get(id))行中失敗,但存在以下異常
groovy.lang.MissingMethodException: No signature of method:
net.domain.Event.addToBundles() is applicable for argument
types: (net.domain.Bundle) values: [Test Bundle]
Possible solutions: getBundles()
at net.service.BundleService.$tt__assignEvent(BundleService.groovy:101)
問題在於由於沒有hasMany集合“ bundles”,應由Grails動態將方法addToBundles()添加到Event類。 如前所述,如果您運行應用程序並使用此服務,則方法就存在,並且一切正常。
我嘗試更改測試的基類(從Specification到IntegrationSpec),因為我相信這里是管理動態功能以及事務管理和其他用於集成測試的內容的地方,但是沒有用。
是否有任何理由為什么在集成測試的上下文中不存在應在服務中使用的此方法? 謝謝
您在測試類中缺少grails.test.mixin.Mock
批注。 Grails單元測試使用此mixin生成類的所有域相關方法,因此您可以在單元測試中正確使用此域。 這樣的事情應該可以解決問題:
@Mock([Event])
class BundleServiceIntegrationSpec extends Specification {
BundleService bundleService
EventService eventService
private BundleTestHelper bundleHelper = new BundleTestHelper()
...
void '04. Test deleteBundleAndAssets method'() {
when: 'a new Bundle is created'
Bundle bundle = bundleHelper.createBundle(project, 'Test Bundle')
and: 'a new Event is created'
Event event = eventService.create(project, 'Test Event')
and: 'the above Bundle is assigned to the Event'
bundleService.assignEvent(event, [bundle.id])
...
}
有關測試域類的更多信息,請參見: https : //grails.github.io/grails2-doc/2.4.5/guide/testing.html#unitTestingDomains
@Szymon Stepniak感謝您的回答,對於您的答復太晚表示抱歉。 我已經測試了您的建議,但是沒有用。 稍后我讀到grails.test.mixin.Mock
批注僅用於單元測試,不應在集成測試中使用。 @TestFor
和@TestMixin
批注也是如此(我已經在這篇文章中閱讀了此內容)。
因此,在此之后,一個工作中的同事建議我在其他測試中搜索這種注釋,以為這可能會導致測試之間的某種測試污染,並在先前運行的其中一個測試中刪除了@TestFor
注釋后作為整個集成測試套件的一部分,我發布的失敗測試開始起作用。 最奇怪的事情(來自編譯器的抱怨是沒有抱怨的)是令人討厭的測試(我從中刪除了@TestFor
批注的測試)全部通過了綠色測試,甚至沒有失敗!
因此,如果有人遇到類似的問題,我建議在整個集成測試套件中的任何位置搜索這種單元測試注釋,並刪除它,因為編譯器不會抱怨,但是以我的經驗,它可能會對其他測試產生影響,並且可以導致非常奇怪的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.