我如何在 Kotlin 中管理单元测试资源,例如 starting/stopping 数据库连接或嵌入式 elasticsearch 服务器?

How do I manage unit test resources in Kotlin, such as starting/stopping a database connection or an embedded elasticsearch server?

在我的 Kotlin JUnit 测试中,我想 start/stop 嵌入式服务器并在我的测试中使用它们。

我尝试在我的测试 class 中的一个方法上使用 JUnit @Before 注释并且它工作正常,但这不是正确的行为,因为它运行每个测试用例而不是只运行一次.

因此我想在一个方法上使用 @BeforeClass 注释,但是将它添加到一个方法中会导致错误提示它必须在一个静态方法上。 Kotlin 似乎没有静态方法。然后这同样适用于静态变量,因为我需要保留对嵌入式服务器的引用以供在测试用例中使用。

那么如何为我的所有测试用例只创建一次这个嵌入式数据库?

class MyTest {
    @Before fun setup() {
       // works in that it opens the database connection, but is wrong 
       // since this is per test case instead of being shared for all
    }

    @BeforeClass fun setupClass() {
       // what I want to do instead, but results in error because 
       // this isn't a static method, and static keyword doesn't exist
    }

    var referenceToServer: ServerType // wrong because is not static either

    ...
}

注: 这个问题是作者(Self-Answered Questions)特意写的,所以常见的Kotlin话题的答案是出现在 SO.

您的单元测试 class 通常需要一些东西来管理一组测试方法的共享资源。在 Kotlin 中,您可以不在测试 class 中使用 @BeforeClass@AfterClass,而是在其 companion object along with the @JvmStatic annotation.

中使用

测试的结构 class 看起来像:

class MyTestClass {
    companion object {
        init {
           // things that may need to be setup before companion class member variables are instantiated
        }

        // variables you initialize for the class just once:
        val someClassVar = initializer() 

        // variables you initialize for the class later in the @BeforeClass method:
        lateinit var someClassLateVar: SomeResource 
  
        @BeforeClass @JvmStatic fun setup() {
           // things to execute once and keep around for the class
        }

        @AfterClass @JvmStatic fun teardown() {
           // clean up after this class, leave nothing dirty behind
        }
    }

    // variables you initialize per instance of the test class:
    val someInstanceVar = initializer() 

    // variables you initialize per test case later in your @Before methods:
    var lateinit someInstanceLateZVar: MyType 

    @Before fun prepareTest() { 
        // things to do before each test
    }

    @After fun cleanupTest() {
        // things to do after each test
    }

    @Test fun testSomething() {
        // an actual test case
    }

    @Test fun testSomethingElse() {
        // another test case
    }

    // ...more test cases
}  

鉴于以上内容,您应该阅读以下内容:

  • companion objects - 类似于 Java 中的 Class 对象,但每个 class 的单例不是静态的
  • @JvmStatic - 将伴生对象方法转换为外部 class 上的静态方法的注释,用于 Java interop
  • lateinit - 允许 var 属性 在你有一个明确定义的生命周期后初始化
  • Delegates.notNull() - 可以代替 lateinit 用于 属性,在读取之前应至少设置一次。

下面是管理嵌入式资源的 Kotlin 测试 classes 的更完整示例。

第一个是从Solr-Undertow tests复制和修改的,在测试用例运行之前,配置并启动一个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")

            // make sure no system properties are set that could interfere with test
            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() {
            // don't leave any test files behind
            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() {
        // anything before each test?
    }

    @After fun cleanupTest() {
        // make sure test cores do not bleed over between test cases
        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)
    }

    // ... other test cases
}

还有另一个作为嵌入式数据库启动的本地 AWS DynamoDB(从 Running AWS DynamoDB-local embedded 复制并稍作修改)。此测试必须在其他任何事情发生之前破解 java.library.path,否则本地 DynamoDB(将 sqlite 与二进制库一起使用)不会 运行。然后它启动一个服务器来为所有测试 classes 共享,并清理测试之间的临时数据。测试:

class TestAccountManager {
    companion object {
        init {
            // we need to control the "java.library.path" or sqlite cannot find its libraries
            val dynLibPath = File("./src/test/dynlib/").absoluteFile
            System.setProperty("java.library.path", dynLibPath.toString());

            // TEST HACK: if we kill this value in the System classloader, it will be
            // recreated on next access allowing java.library.path to be reset
            val fieldSysPath = ClassLoader::class.java.getDeclaredField("sys_paths")
            fieldSysPath.setAccessible(true)
            fieldSysPath.set(null, null)

            // ensure logging always goes through Slf4j
            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() {
            // do not use ServerRunner, it is evil and doesn't set the port correctly, also
            // it resets logging to be off.
            localDb = DynamoDBProxyServer(localDbPort, LocalDynamoDBServerHandler(
                    LocalDynamoDBRequestHandler(0, true, null, true, true), null)
            )
            localDb.start()

            // fake credentials are required even though ignored
            val auth = BasicAWSCredentials("fakeKey", "fakeSecret")
            dbClient = AmazonDynamoDBClient(auth) initializedWith {
                signerRegionOverride = "us-east-1"
                setEndpoint("http://localhost:$localDbPort")
            }
            dynamo = DynamoDB(dbClient)

            // create the tables once
            AccountManagerSchema.createTables(dbClient)

            // for debugging reference
            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() {
        // insert commonly used test data
        setupStaticBillingData(dbClient)
    }

    @After fun cleanupTest() {
        // delete anything that shouldn't survive any test case
        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)
    }

    // ...more test cases

}

注意:示例的某些部分缩写为...

在测试中使用 before/after 回调管理资源,显然有其优点:

  • 测试 "atomic"。测试作为一个整体执行,包含所有回调 人们不会忘记在测试之前启动依赖服务并在测试完成后将其关闭。如果操作得当,执行回调将适用于任何环境。
  • 测试是独立的。没有外部数据或设置阶段,所有内容都包含在一些测试中 类.

它也有一些缺点。其中一个重要的是它污染了代码,使代码违反了单一职责原则。测试现在不仅可以测试某些东西,还可以执行重量级的初始化和资源管理。在某些情况下可能没问题(比如 configuring an ObjectMapper),但修改 java.library.path 或生成另一个进程(或进程内嵌入式数据库)并不是那么无辜。

为什么不将这些服务视为符合 "injection" 条件的测试的依赖项,如 12factor.net 所述。

这样您就可以在测试代码之外的某处启动和初始化依赖服务。

如今虚拟化和容器几乎无处不在,大多数开发人员的机器都能够 运行 Docker。大多数应用程序都有一个 dockerized 版本:Elasticsearch, DynamoDB, PostgreSQL 等等。 Docker 是您测试所需的外部服务的完美解决方案。

  • 它可以是 运行s 是开发人员每次要执行测试时手动 运行 的脚本。
  • 它可以是构建工具的任务 运行(例如 Gradle 有很棒的 dependsOn and finalizedBy DSL 用于定义依赖项)。当然,任务可以执行开发人员使用 shell-outs / process execs 手动执行的相同脚本。
  • 可以是task run by IDE before test execution。同样,它可以使用相同的脚本。
  • 大多数 CI / CD 提供商有一个概念 "service" — 一个外部依赖(过程),运行 与您的构建并行,可以通过它通常的 SDK 访问/ 连接器 / API: Gitlab, Travis, Bitbucket, AppVeyor, Semaphore, …

这种方法:

  • 将您的测试代码从初始化逻辑中解放出来。你的测试只会测试,什么都不做。
  • 解耦代码和数据。现在可以通过使用其本机工具集将新数据添加到依赖服务中来添加新的测试用例。 IE。对于 SQL 个数据库,您将使用 SQL,对于 Amazon DynamoDB,您将使用 CLI 创建表并放置项目。
  • 更接近于生产代码,当您的 "main" 应用程序启动时,您显然不会启动这些服务。

当然,它有它的缺陷(基本上,我开始的陈述):

  • 测试不多"atomic"。依赖服务必须在测试执行之前以某种方式启动。不同环境启动方式可能不同:开发者机器或CI、IDE或构建工具CLI.
  • 测试不是独立的。现在您的种子数据甚至可能打包在图像中,因此更改它可能需要重建不同的项目。