您的单元测试类通常需要一些东西来管理一组测试方法的共享资源。在Kotlin中,您可以使用@BeforeClass
而@AfterClass
不是在测试类中使用,而可以在其伴随对象以及@JvmStatic
注释中使用。
测试类的结构如下所示:
class MyTestClass {
companion object {
init {
}
val someClassVar = initializer()
lateinit var someClassLateVar: SomeResource
@BeforeClass @JvmStatic fun setup() {
}
@AfterClass @JvmStatic fun teardown() {
}
}
val someInstanceVar = initializer()
var lateinit someInstanceLateZVar: MyType
@Before fun prepareTest() {
}
@After fun cleanupTest() {
}
@Test fun testSomething() {
}
@Test fun testSomethingElse() {
}
}
鉴于以上所述,您应该阅读以下内容:
以下是管理嵌入式资源的Kotlin测试类的完整示例。
第一个是从Solr-Undertow测试中复制和修改的,在运行测试用例之前,请配置并启动Solr-Undertow服务器。测试运行后,它将清除测试创建的所有临时文件。它还可以在运行测试之前确保环境变量和系统属性正确。在测试用例之间,它会卸载所有临时加载的Solr内核。考试:
class TestServerWithPlugin {
companion object {
val workingDir = Paths.get("test-data/solr-standalone").toAbsolutePath()
val coreWithPluginDir = workingDir.resolve("plugin-test/collection1")
lateinit var server: Server
@BeforeClass @JvmStatic fun setup() {
assertTrue(coreWithPluginDir.exists(), "test core w/plugin does not exist $coreWithPluginDir")
resetEnvProxy()
cleanSysProps()
routeJbossLoggingToSlf4j()
cleanFiles()
val config = mapOf(...)
val configLoader = ServerConfigFromOverridesAndReference(workingDir, config) verifiedBy { loader ->
...
}
assertNotNull(System.getProperty("solr.solr.home"))
server = Server(configLoader)
val (serverStarted, message) = server.run()
if (!serverStarted) {
fail("Server not started: '$message'")
}
}
@AfterClass @JvmStatic fun teardown() {
server.shutdown()
cleanFiles()
resetEnvProxy()
cleanSysProps()
}
private fun cleanSysProps() { ... }
private fun cleanFiles() {
coreWithPluginDir.resolve("data").deleteRecursively()
Files.deleteIfExists(coreWithPluginDir.resolve("core.properties"))
Files.deleteIfExists(coreWithPluginDir.resolve("core.properties.unloaded"))
}
}
val adminClient: SolrClient = HttpSolrClient("http://localhost:8983/solr/")
@Before fun prepareTest() {
}
@After fun cleanupTest() {
unloadCoreIfExists("tempCollection1")
unloadCoreIfExists("tempCollection2")
unloadCoreIfExists("tempCollection3")
}
private fun unloadCoreIfExists(name: String) { ... }
@Test
fun testServerLoadsPlugin() {
println("Loading core 'withplugin' from dir ${coreWithPluginDir.toString()}")
val response = CoreAdminRequest.createCore("tempCollection1", coreWithPluginDir.toString(), adminClient)
assertEquals(0, response.status)
}
}
另一个作为嵌入式数据库的启动AWS DynamoDB本地(已从运行AWS DynamoDB-local Embedded进行了稍微复制和修改)。此测试必须先破解,java.library.path
然后再进行其他操作,否则本地DynamoDB(将sqlite与二进制库一起使用)将无法运行。然后,它启动服务器以共享所有测试类,并清除测试之间的临时数据。考试:
class TestAccountManager {
companion object {
init {
val dynLibPath = File("./src/test/dynlib/").absoluteFile
System.setProperty("java.library.path", dynLibPath.toString());
val fieldSysPath = ClassLoader::class.java.getDeclaredField("sys_paths")
fieldSysPath.setAccessible(true)
fieldSysPath.set(null, null)
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.Slf4jLog")
}
private val localDbPort = 19444
private lateinit var localDb: DynamoDBProxyServer
private lateinit var dbClient: AmazonDynamoDBClient
private lateinit var dynamo: DynamoDB
@BeforeClass @JvmStatic fun setup() {
localDb = DynamoDBProxyServer(localDbPort, LocalDynamoDBServerHandler(
LocalDynamoDBRequestHandler(0, true, null, true, true), null)
)
localDb.start()
val auth = BasicAWSCredentials("fakeKey", "fakeSecret")
dbClient = AmazonDynamoDBClient(auth) initializedWith {
signerRegionOverride = "us-east-1"
setEndpoint("http://localhost:$localDbPort")
}
dynamo = DynamoDB(dbClient)
AccountManagerSchema.createTables(dbClient)
dynamo.listTables().forEach { table ->
println(table.tableName)
}
}
@AfterClass @JvmStatic fun teardown() {
dbClient.shutdown()
localDb.stop()
}
}
val jsonMapper = jacksonObjectMapper()
val dynamoMapper: DynamoDBMapper = DynamoDBMapper(dbClient)
@Before fun prepareTest() {
setupStaticBillingData(dbClient)
}
@After fun cleanupTest() {
deleteAllInTable<Account>()
deleteAllInTable<Organization>()
deleteAllInTable<Billing>()
}
private inline fun <reified T: Any> deleteAllInTable() { ... }
@Test fun testAccountJsonRoundTrip() {
val acct = Account("123", ...)
dynamoMapper.save(acct)
val item = dynamo.getTable("Accounts").getItem("id", "123")
val acctReadJson = jsonMapper.readValue<Account>(item.toJSON())
assertEquals(acct, acctReadJson)
}
}
注意:示例的某些部分缩写为...