gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:48:29 26 4
gpt4 key购买 nike

我正在使用Grails 2.5.4开发项目,目前正在尝试运行一些未运行的集成测试。
我已经调试了该问题,并发现在集成测试中运行时显然没有要测试的服务上的某些动态方法(如果在应用程序的上下文中运行该方法,则所有方法都可以使用)。在我尝试运行的许多测试中都会发生这种情况,我选择了其中的一个作为示例,但其他未通过的测试则存在相同的问题。

我有这个 Realm 类(class)

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),因为我相信这里是管理动态功能以及事务管理和集成测试其他内容的地方,但是没有用。

是否有任何理由为什么在集成测试的上下文中不存在应在服务中使用的此方法?谢谢

最佳答案

您在测试类(class)中缺少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])
...
}

More about testing domain classes can be found here: https://grails.github.io/grails2-doc/2.4.5/guide/testing.html#unitTestingDomains

关于grails - 运行集成测试时不存在Grails动态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52505192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com