Guice 模块测试:需要绑定带注释的字符串

Guice module test: require binding of annotated strings

我正在尝试为我在多个项目中使用的库存储库中的常用 guice 模块编写一些测试。一些模块具有注入项目配置的注释字符串注入。例如,我有一个 cassandra 模块,它需要主机、端口和其他配置的字符串绑定:

class CassandraModule : AbstractModule() {
companion object {
    const val CASSANDRA_HOST = "cassandra.host"
    const val CASSANDRA_PORT = "cassandra.port"
    ...

    const val MY_CASSANDRA_READ = "casandra.db.read"
    const val MY_CASSANDRA_WRITE = "casandra.db.write"
}

override fun configure() {
}

@Provides
@Singleton
@Named(MY_CASSANDRA_READ)
fun provideCassandraReadCluster(
    @Named(CASSANDRA_HOST) host: String,
    @Named(CASSANDRA_PORT) port: Int,
    @Named(CASSANDRA_DATACENTER) dc: String
): Cluster {
    val queryOptions = QueryOptions()
    queryOptions.consistencyLevel = ConsistencyLevel.LOCAL_ONE

    val cluster = Cluster.builder()
        .addContactPoint(host)
        .withPort(port)
        .withLoadBalancingPolicy(DCAwareRoundRobinPolicy(dc))
        .withQueryOptions(queryOptions)
        .build()
    return cluster
}

@Provides
@Singleton
@Named(MY_CASSANDRA_READ)
fun provideCassandraReadSession(
    @Named(MY_CASSANDRA_READ) cluster: Cluster,
    @Named(CASSANDRA_KEYSPACE) keyspace: String
): Session {
    return cluster.connect(keyspace)
}
...
}

所有这些配置字符串绑定都应该通过 Property 绑定来自其他项目,这些绑定将此库模块用作依赖项。我如何模拟这些带注释的字符串属性?

你为什么要嘲笑他们?您可以在提供这些值的测试中注册一个附加模块。