Tested class:
public class ClassForTest {
public String hello(){
return "hello " + getClassName();
}
public String getClassName(){
return ClassForTest.class.getName();
}
}
Spock class:
class ClassForSpockTest extends Specification{
def setupSpec(){
ClassForTest.metaClass.getClassName={"ClassForSpockTest"}
}
def "override test"(){
setup:
ClassForTest cft = new ClassForTest()
expect:
cft.getClassName() == "ClassForSpockTest"
}
def "mock test"(){
setup:
ClassForTest cft = new ClassForTest()
expect:
cft.hello() == "hello ClassForSpockTest"
}
}
override test test is passed! Mock test is crashing, cft.hello() return "hello ClassForTest"
You can't use the metaclass to override a method call in a Java class from another method in that class. This is a limitation of spock, Java, and groovy. In this case, you have to use other mocking techniques. For example, you can use subclassing:
setup:
ClassForTest cft = new ClassForTest() {
String getClassName() {"ClassForSpockTest"}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.