🔀 Merge “release/v81” into “master”
[Sone.git] / src / test / kotlin / net / pterodactylus / sone / test / Guice.kt
1 package net.pterodactylus.sone.test
2
3 import com.google.inject.*
4 import com.google.inject.name.*
5 import org.hamcrest.MatcherAssert.*
6 import org.hamcrest.Matchers.*
7 import org.mockito.*
8 import javax.inject.Provider
9 import kotlin.reflect.*
10
11 fun <T : Any> KClass<T>.isProvidedBy(instance: T) = Module { it.bind(this.java).toProvider(Provider<T> { instance }) }
12 fun <T : Any> KClass<T>.withNameIsProvidedBy(instance: T, name: String) = Module { it.bind(this.java).annotatedWith(Names.named(name)).toProvider(Provider<T> { instance }) }
13 fun <T : Any> KClass<T>.isProvidedBy(provider: com.google.inject.Provider<T>) = Module { it.bind(this.java).toProvider(provider) }
14 fun <T : Any> KClass<T>.isProvidedBy(provider: KClass<out Provider<T>>) = Module { it.bind(this.java).toProvider(provider.java) }
15 inline fun <reified T : Any> KClass<T>.isProvidedByMock() = Module { it.bind(this.java).toProvider(Provider<T> { mock() }) }
16 inline fun <reified T : Any> KClass<T>.isProvidedByDeepMock() = Module { it.bind(this.java).toProvider(Provider<T> { deepMock() }) }
17
18 inline fun <reified T : Any> Injector.getInstance(annotation: Annotation? = null): T = annotation
19                 ?.let { getInstance(Key.get(object : TypeLiteral<T>() {}, it)) }
20                 ?: getInstance(Key.get(object : TypeLiteral<T>() {}))
21
22
23 inline fun <reified T : Any> Injector.verifySingletonInstance(annotation: Annotation? = null) {
24         val firstInstance = getInstance<T>(annotation)
25         val secondInstance = getInstance<T>(annotation)
26         assertThat(firstInstance, sameInstance(secondInstance))
27 }
28
29 fun <T : Any> supply(javaClass: Class<T>): Source<T> = object : Source<T> {
30         override fun fromInstance(instance: T) = Module { it.bind(javaClass).toInstance(instance) }
31         override fun byInstance(instance: T) = Module { it.bind(javaClass).toProvider(Provider<T> { instance }) }
32         override fun byProvider(provider: com.google.inject.Provider<T>) = Module { it.bind(javaClass).toProvider(provider) }
33         override fun byProvider(provider: Class<Provider<T>>) = Module { it.bind(javaClass).toProvider(provider) }
34         override fun byMock() = Module { it.bind(javaClass).toInstance(Mockito.mock(javaClass)) }
35 }
36
37 interface Source<T : Any> {
38         fun fromInstance(instance: T): Module
39         fun byInstance(instance: T): Module
40         fun byProvider(provider: com.google.inject.Provider<T>): Module
41         fun byProvider(provider: Class<Provider<T>>): Module
42         fun byMock(): Module
43 }