以下是我们正在做的事情,它在grails 2.0.0和spock 0.6
中起作用简单域名:
package com.grails
class User {
String name, password
def methodWithNoArguments(){
return "Object: methodWithNoArguments"
}
static constraints = {
}
}
单位规格:
package com.grails
import spock.lang.*
import grails.test.mixin.TestFor
import grails.test.mixin.Mock
import grails.test.GrailsMock
@TestFor(UserController) // testing for
@Mock([User]) // collaborators class
UserControllerSpec extends Specification {
// DOES NOT work in 2.2.3 spock 0.7,
// WORKS in grails-2.0.0 spock 0.6
def 'create a Domain collaborator using Mock'() {
given: 'user'
// can't mock this anymore, causes classcast exception.
User user = Mock(User)
user.methodWithNoArguments() >> { "Mock: (3) methodWithNoArguments" }
when: 'we call the method'
def val1 = user.methodWithNoArguments()
then: 'value should be from the mocked method'
val1 == "Mock: (3) methodWithNoArguments"
} }
以上在grails 2.2.3和spock 0.7中导致以下异常。注意(它适用于grails-2.0.0和spock 0.6)
| java.lang.ClassCastException:com.grails.User无法强制转换为net.sf.cglib.proxy.Factory 在org.spockframework.mock.runtime.ProxyBasedMockFactory $ CglibMockFactory.createMock(ProxyBasedMockFactory.java:93) 在org.spockframework.mock.runtime.ProxyBasedMockFactory.create(ProxyBasedMockFactory.java:49) 在org.spockframework.mock.runtime.JavaMockFactory.create(JavaMockFactory.java:51) 在org.spockframework.mock.runtime.CompositeMockFactory.create(CompositeMockFactory.java:44) 在org.spockframework.lang.SpecInternals.createMock(SpecInternals.java:47) 在org.spockframework.lang.SpecInternals.createMockImpl(SpecInternals.java:282) at org.spockframework.lang.SpecInternals.MockImpl(SpecInternals.java:99) 在com.grails.UserControllerSpec.create使用Mock的域协作者(UserControllerSpec.groovy:94)
想知道是否存在一些不兼容的库,这里是BuildConfig.groovy
dependencies {
test "org.spockframework:spock-grails-support:0.7-groovy-2.0"
}
plugins {
runtime ":hibernate:$grailsVersion"
runtime ":jquery:1.8.3"
runtime ":resources:1.2"
build ":tomcat:$grailsVersion"
runtime ":database-migration:1.3.2"
compile ':cache:1.0.1'
test(":spock:0.7") {
exclude "spock-grails-support"
}
}
样本测试应用程序位于git@github.com:nbostech/grails-spock-2.2.3.git
git checkout grails-2.0.0; < 2.0.0> / bin / grails test-app --unit UserControllerSpec; //所有测试都通过
git checkout master; < 2.2.3> / bin / grails test-app --unit UserControllerSpec; //其中一个测试失败..
答案 0 :(得分:2)
Grails和Spock模拟不是以这种方式混合的。要么是Grails @Mock
,要么是Spock Mock()
。