Skip to content

Instantly share code, notes, and snippets.

@Singleton
class GreetingServiceImpl @Inject constructor(private val messageData: MessageData, private val timeService: TimeService) :
GreetingService {
@Singleton
class TimeServiceImpl @Inject constructor() : TimeService {
data class MessageData @Inject constructor(val welcomeMessage: String)
@RunWith(MockitoJUnitRunner::class)
class GreetingServiceTest {
private lateinit var greetingService: GreetingService
@Mock
lateinit var timeService: TimeService
@Before
fun setup() {
class MainActivity : AppCompatActivity() {
@Inject
lateinit var greetingService: GreetingService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
(application as DaggerApplication).appComponent.inject(this)
class DaggerApplication : Application() {
val appComponent: AppComponent by lazy {
DaggerAppComponent.factory().create("welcome to Dagger")
}
}
@Singleton
@Component(modules = [DaggerModule::class])
interface AppComponent {
fun inject(mainActivity: MainActivity)
@Component.Factory
interface Factory {
fun create(@BindsInstance welcomeMessage: String): AppComponent
@Module
interface DaggerModule {
@Binds
fun provideTimeService(impl: TimeServiceImpl): TimeService
@Binds
fun provideGreetingSersvice(impl: GreetingServiceImpl): GreetingService
}
class GreetingServiceTest {
@Test
fun testGreetingInTheMorning() {
val testContainer = Kodein {
import(kodeinModule)
bind<TimeService>(overrides = true) with singleton {
object : TimeService {
override fun getHourOfDay(): Int = 9
class MainActivity : AppCompatActivity(), KodeinAware {
override val kodein by closestKodein()
private val greetingService by instance<GreetingService>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
class KodeinApplication : Application(), KodeinAware {
override val kodein = Kodein.lazy {
import(kodeinModule)
}
}
val kodeinModule = Kodein.Module(name = "appmodule") {
bind() from singleton { MessageData() }
bind<TimeService>() with singleton { TimeServiceImpl() }
bind<GreetingService>() with singleton {
GreetingServiceImpl(instance(), instance()) }
}