使用文件 class 进行 Grails spock 测试
Grails spock Testing with File class
我有一种方法可以根据从另一个文件复制的内容创建一个文件。
喜欢下面
private cloneBaseFile(fileName, ddi, ddd){
def config = grailsApplication.config.kicksim.fileConstants
String baseFileContents = new File(config.baseFile).getText('UTF-8')
def help = handleString("${ddd}.${ddi}")
baseFileContents = baseFileContents.replaceAll("DDDDDI", help);
def f1= new File(fileName)
f1 << baseFileContents
return fileName
}
我想知道如何对其进行单元测试。
我认为您应该将此方法的职责分开 (c.f。Single Responsibility Principle)。如果您还没有 Robert Martin 的《整洁代码》一书,那么我强烈推荐它:他的代码是一件艺术品,教会了我很多东西。
cloneBaseFile()
实际上做了很多事情:它打开一个文件,获取文件的内容,在 handleString()
中做一些事情(我不知道是什么),替换文件内容的修改版本,然后最终保存文件。
怎么样(作为10人的首发):
private cloneBaseFile(fileName, ddi, ddd){
def config = grailsApplication.config.kicksim.fileConstants
String baseFileContents = getFileContents(config.baseFile)
baseFileContents = handleFileContents(baseFileContents)
return createNewFileWithContents(fileName, baseFileContents)
}
String getFileContents(String fileName) {
String contents = new File(fileName).getText('UTF-8')
return contents
}
String handleFileContents(String oldContents) {
def help = handleString("${ddd}.${ddi}")
return oldContents.replaceAll("DDDDDI", help);
}
String createNewFileWithContents(String newFileName, String newContents) {
def f1= new File(newFileName)
f1 << newContents
return newFileName
}
现在您有多个小方法,每个方法都可以更容易地进行测试。您还需要测试 handleString()
方法。
我有一种方法可以根据从另一个文件复制的内容创建一个文件。 喜欢下面
private cloneBaseFile(fileName, ddi, ddd){
def config = grailsApplication.config.kicksim.fileConstants
String baseFileContents = new File(config.baseFile).getText('UTF-8')
def help = handleString("${ddd}.${ddi}")
baseFileContents = baseFileContents.replaceAll("DDDDDI", help);
def f1= new File(fileName)
f1 << baseFileContents
return fileName
}
我想知道如何对其进行单元测试。
我认为您应该将此方法的职责分开 (c.f。Single Responsibility Principle)。如果您还没有 Robert Martin 的《整洁代码》一书,那么我强烈推荐它:他的代码是一件艺术品,教会了我很多东西。
cloneBaseFile()
实际上做了很多事情:它打开一个文件,获取文件的内容,在 handleString()
中做一些事情(我不知道是什么),替换文件内容的修改版本,然后最终保存文件。
怎么样(作为10人的首发):
private cloneBaseFile(fileName, ddi, ddd){
def config = grailsApplication.config.kicksim.fileConstants
String baseFileContents = getFileContents(config.baseFile)
baseFileContents = handleFileContents(baseFileContents)
return createNewFileWithContents(fileName, baseFileContents)
}
String getFileContents(String fileName) {
String contents = new File(fileName).getText('UTF-8')
return contents
}
String handleFileContents(String oldContents) {
def help = handleString("${ddd}.${ddi}")
return oldContents.replaceAll("DDDDDI", help);
}
String createNewFileWithContents(String newFileName, String newContents) {
def f1= new File(newFileName)
f1 << newContents
return newFileName
}
现在您有多个小方法,每个方法都可以更容易地进行测试。您还需要测试 handleString()
方法。