如何避免在Spock中强制转换参数

问题描述:

我想从存储库中获取列表并声明其内容.

I want to get a List from repository and assert its contents.

在下面的代码中,我收到一条警告,指出不能将Object分配给List

In following code I get a warning that states that Object cannot be assigned to List

有什么方法可以添加更好的参数来处理这种情况?

Is there any way to add better argument to handle such case?

myDomainObjectRepository.save(_) >> { arguments ->
   final List<MyDomainObject> myDomainObjects = arguments[0]
   assert myDomainObjects == [new MyDomainObject(someId, someData)]
}

要详细说明蛋白石,请执行以下操作:

To elaborate on Opals answer: There are two parts and a footnote in the docs that are relevant here:

如果闭包声明了一个无类型的参数,它将被传递给 方法的参数列表:

If the closure declares a single untyped parameter, it gets passed the method’s argument list:

还有

在大多数情况下,直接访问 方法的参数.如果闭包声明了多个参数,或者 单个类型的参数,方法参数将被一对一映射 到关闭参数[脚注]:

In most cases it would be more convenient to have direct access to the method’s arguments. If the closure declares more than one parameter or a single typed parameter, method arguments will be mapped one-by-one to closure parameters[footnote]:

脚注:

闭包参数的解构语义直接来自 时髦.

The destructuring semantics for closure arguments come straight from Groovy.

问题是您只有一个参数List,并且由于删除了泛型,因此无法确定您是否真正要拆开列表.

The problem is that you have a single argument List, and since generics are erased groovy can't decide that you actually want to unwrap the list.

因此,一个非List参数可以正常工作:

So a single non-List argument works fine:

myDomainObjectRepository.save(_) >> { MyDomainObject myDomainObject ->
   assert myDomainObject == new MyDomainObject(someId, someData)
}

List参数加上第二个参数,例如save(List domain, boolean flush)

or a List argument combined with a second, e.g., save(List domain, boolean flush)

myDomainObjectRepository.save(_, _) >> { List<MyDomainObject> myDomainObjects, boolean flush -> 
   assert myDomainObjects == [new MyDomainObject(someId, someData)]
}

因此,对于这种极端情况,文档有些误导.恐怕您会为这种情况而烦恼.

So the docs are a little bit misleading about this edge case. I'm afraid that you are stuck with casting for this case.

如果执行此操作,您应该可以摆脱IDE警告.

You should be able to get rid of the IDE warnings if you do this.

myDomainObjectRepository.save(_) >> { List<List<MyDomainObject>> arguments ->
   List<MyDomainObject> myDomainObjects = arguments[0]
   assert myDomainObjects == [new MyDomainObject(someId, someData)]
}