我决定使用File Factory来模拟File对象的构造。Groovy嘲笑Spock的文件工厂
class FileClass {
def basePath
def listObjects = []
def createFilePerObject() {
listObjects.each {currentObject ->
// Use some other libraries for mocking(cant run PowerMockito, Gareth Davis adviced me to use JMockit)
// File currentFile = new File("${basePath.toString()}/${currentObject.objectName}")
//File factory(The simplest of the solutions)...
File currentFile = FileFactory.makeFile("${basePath.toString()}/${currentObject.objectName}")
currentFile.write currentObject.objectContent //Verify this behaviour!!
}
}
}
class SimpleObject {
String objectName
String objectContent
}
//Really simple
class FileFactory {
def static makeFile(String pathFileName) {
return new File(pathFileName);
}
}
而且测试:
class FileClassTest extends Specification {
FileClass fileClass
def "test simple object"() {
def listObjects = []
SimpleObject object1 = new SimpleObject(objectName: "First object", objectContent: "First object content")
SimpleObject object2 = new SimpleObject(objectName: "Second object", objectContent: "Second object content")
SimpleObject object3 = new SimpleObject(objectName: "Third object", objectContent: "Third object content")
SimpleObject object4 = new SimpleObject(objectName: "Fourth object", objectContent: "Fourth object content")
listObjects << object1
listObjects << object2
listObjects << object3
listObjects << object4
fileClass = new FileClass(listObjects: listObjects, basePath: ".")
def mockFile = Mock(File)
def mockFileFactory = new MockFor(FileFactory)
mockFileFactory.demand.makeFile {mockFile} //Return the mocked file...
when:
mockFileFactory.use {
fileClass.createFilePerObject()
}
then:
1 * mockFile.write(_)
}
}
的事情是,它失败的NullPointerException!?
使用我到调试器:
currentFile.write currentObject.objectContent //Verify this behaviour!!
而且,经核实,“当前文件”真的是在测试中指定的嘲笑文件。 “currentObject.objectContent”不为null,“currentFile”不为null。
突然,它跳到BaseSpecRunner.java这种方法:
protected Object invokeRaw(Object target, MethodInfo method, Object[] arguments) {
if (method.isStub()) return null;
try {
return method.getReflection().invoke(target, arguments);
} catch (InvocationTargetException e) {
//Here it fails!
runStatus = supervisor.error(new ErrorInfo(method, e.getTargetException()));
return null;
} catch (Throwable t) {
Error internalError =
new InternalSpockError("Failed to invoke method '%s'", t).withArgs(method.getReflection().getName());
runStatus = supervisor.error(new ErrorInfo(method, internalError));
return null;
}
}
“的InvocationTargetException是经过检查的异常包装由调用方法或构造函数抛出的异常。”大。
任何想法?
谢谢。