Search code examples
javaunit-testingkotlinguice

Guice module test: require binding of annotated strings


I'm trying to write some tests for my common guice modules in my library repo that I use across several projects. Some modules have annotated string injections that inject project configurations. For example, I have a cassandra module that requires String bindings for host, port and other configs:

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)
}
...
}

All these config string bindings should come from other projects via Property bindings that use this library module as a dependency. How do I mock these annotated string properties?


Solution

  • Why do you want to mock them? You could register an addional module in your tests that provides those values.