Sug*_*lai 7 java groovy unit-testing spock
我正在尝试readAttributes使用 groovy 的metaClass约定来模拟静态方法之一,但实际方法被调用。
这就是我嘲笑静态函数的方式:
def "test"() {
File file = fold.newFile('file.txt')
Files.metaClass.static.readAttributes = { path, cls ->
null
}
when:
fileUtil.fileCreationTime(file)
then:
1 * fileUtil.LOG.debug('null attribute')
}
Run Code Online (Sandbox Code Playgroud)
我在这里做错了吗?
我的java方法
public Object fileCreationTime(File file) {
try {
BasicFileAttributes attributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
if(attributes == null) {
LOG.debug("null attribute");
}
//doSomething
} catch (IOException exception) {
//doSomething
}
return new Object();
}
Run Code Online (Sandbox Code Playgroud)
我使用一级间接解决了这个问题。我创建了一个实例方法,test class它就像这个静态调用的包装器。
public BasicFileAttributes readAttrs(File file) throws IOException {
return Files.readAttributes(file.toPath(), BasicFileAttributes.class);
}
Run Code Online (Sandbox Code Playgroud)
从测试中我嘲笑了实例方法。
FileUtil util = Spy(FileUtil);
util.readAttrs(file) >> { null }
Run Code Online (Sandbox Code Playgroud)
这解决了我的问题。
| 归档时间: |
|
| 查看次数: |
19840 次 |
| 最近记录: |