Spocklight:Java 和 Groovy 应用程序的自动清理资源
💡一则或许对你有用的小广告
欢迎加入小哈的星球 ,你将获得:专属的项目实战 / 1v1 提问 / Java 学习路线 / 学习打卡 / 每月赠书 / 社群讨论
- 新项目:《从零手撸:仿小红书(微服务架构)》 正在持续爆肝中,基于
Spring Cloud Alibaba + Spring Boot 3.x + JDK 17...
,点击查看项目介绍 ;- 《从零手撸:前后端分离博客项目(全栈开发)》 2 期已完结,演示链接: http://116.62.199.48/ ;
截止目前, 星球 内专栏累计输出 82w+ 字,讲解图 3441+ 张,还在持续爆肝中.. 后续还会上新更多项目,目标是将 Java 领域典型的项目都整一波,如秒杀系统, 在线商城, IM 即时通讯,权限管理,Spring Cloud Alibaba 微服务等等,已有 2800+ 小伙伴加入学习 ,欢迎点击围观
Spock 有很多很好的扩展,我们可以在我们的规范中使用。
AutoCleanup
扩展确保每次完成功能方法时都会调用对象的
close()
方法。我们也可以从规范中的
cleanup
方法调用
close()
方法,但使用
@AutoCleanup
注释更容易并立即显示我们的意图。如果我们应用注释的对象没有要调用的
close()
方法,我们可以将方法名称指定为注释的值。最后,如果我们不想看到在调用
close()
方法(或指定的自定义方法名称)时引发的任何异常,我们可以将属性
quiet
设置为
true
。
在下面的示例代码中,我们有一个测试
WatchService
实现的规范。该实现还实现了
Closeable
接口,这意味着我们可以使用
close()
方法正确清理对象。我们还有一个自定义类
WorkDir
,其中包含需要调用的
delete()
方法。
package com.mrhaki.spock
import spock.lang.AutoCleanup
import spock.lang.Specification
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.WatchKey
import java.nio.file.WatchService
import java.util.concurrent.TimeUnit
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE
class WatchSpec extends Specification {
// Use close() method of WatchService
// when feature method is done.
@AutoCleanup
private WatchService watchService
// Use delete() method of WorkDir class
// when feature method is done.
// If the quiet attribute is true, then
// exceptions from the delete() method are
// not shown, otherwise exceptions are reported.
@AutoCleanup(value = 'delete', quiet = true)
private WorkDir testPath = new WorkDir('test-dir')
def setup() {
// Get new watch service.
watchService = FileSystems.default.newWatchService()
// Register for events when a new file is created
// in the testPath directory.
testPath.path.register(watchService, ENTRY_CREATE)
}
def "get notification when file is created"() {
given:
final Path testFile = testPath.path.resolve('test-file')
testFile << 'sample'
and:
final WatchKey watchKey = watchService.poll(10, TimeUnit.SECONDS)
when:
final events = watchKey.pollEvents()
then:
events.size() == 1
events[0].kind() == ENTRY_CREATE
cleanup:
Files.delete(testFile)
}
}
class WorkDir {
private final Path path
WorkDir(final String dir) {
path = Paths.get(dir)
Files.createDirectories(path)
}
Path getPath() {
path
}
void delete() {
Files.deleteIfExists(path)
}
}
使用 Spock 1.0-groovy-2.4 编写。