我试图在我的服务中测试一个方法,但我一直收到错误
目前不支持像[findAll]这样的基于字符串的查询 实施GORM。改为使用标准。
我的服务:
class MyService {
List<Color> colorShade (String shade) {
def shadeId = Shade.findByName(shade).id
return ColorShade.get(shadeId)
}
}
加入Shade
和Color
域
class ColorShade extends Serializable {
Color color
Shade shade
static ColorShade create (Color color, Shade shade, boolean flush = false) {
if (get(shade.id) == null)
new ColorNetwork(color: color, shade: shade).save(flush: flush)
}
static ColorShade get (long shadeId) {
ColorShade.findAll 'from ColorShade where shade.id = :shadeId',
[shadeId: shadeId]
}
static mapping = {
table 'color_shade'
version false
id composite: ['color', 'shade']
}
}
我的规范:test\unit\MyServiceSpec.groovy
我还尝试将其添加到test\integration\MyServiceSpec.groovy
@TestFor(MyServiceSpec)
@Mock([Color, Shade, ColorNetwork])
@TestMixin(DomainClassUnitTestMixin)
class MyServiceSpec extends Specification {
def shade
def color
def setup(){
color = new Color(name: "red")
shade = new Shade(name: "dark")
color.save(flush: true)
shade.save(flush: true)
ColorShade.create(color, shade)
/*
I've also tried:
mockDomain(ColorShade, [[color: color, shade: shade]])
but I get the same error
*/
}
def cleanup () {
}
def "test colorShade" () {
expect:
1 == service.colorShade("dark").size()
}
}
当我运行此测试时出现错误:
String-based queries like [findAll] are currently not supported in this implementation of GORM. Use criteria instead.
问题
注意:这只是我为了问题而创建的示例测试场景。我的实际测试不同,但在这些测试中我遇到了同样的问题。
答案 0 :(得分:2)
如果您使用的是版本4.3.5.4或更高版本的hibernate4插件,那么您可以使用grails.test.mixin.hibernate.HibernateTestMixin
,它在您的单元测试环境中支持完整的Hibernate GORM。您需要在grails-app/conf/BuildConfig.groovy
。
dependencies {
test "org.grails:grails-datastore-test-support:1.0-grails-2.4"
}
然后使用grails.test.mixin.hibernate.HibernateTestMixin
注释注释您的测试。