运行集成测试时不存在的 Grails 动态方法



我正在使用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))
}
}
...
}

然后我运行这个斯波克测试

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)

问题是没有添加方法addToBundles((,该方法应该由Grails动态添加到事件类中,因为hasMany集合"bundles"。正如我提到的,如果您运行应用程序并使用此服务,则该方法就在那里并且一切正常。

我尝试更改测试的基类(从规范到集成规范(,因为我相信这里是管理动态功能以及事务管理以及集成测试的其他东西的地方,但它没有奏效。

有什么理由为什么应该在服务中存在此方法在集成测试的上下文中不存在?谢谢

测试类中缺少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注释的测试(通过全绿色,它甚至没有失败!
因此,如果有人有类似的问题,我建议在整个集成测试套件中的任何位置搜索这种单元测试注释并将其删除,因为编译器不会抱怨,但根据我的经验,它可能会影响其他测试,并可能导致非常奇怪的行为。

最新更新