Skip to content

Instantly share code, notes, and snippets.

@Singleton
@Component(modules = [DaggerModule::class])
interface AppComponent {
fun inject(mainActivity: MainActivity)
@Component.Factory
interface Factory {
fun create(@BindsInstance welcomeMessage: String): AppComponent
class DaggerApplication : Application() {
val appComponent: AppComponent by lazy {
DaggerAppComponent.factory().create("welcome to Dagger")
}
}
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)
@RunWith(MockitoJUnitRunner::class)
class GreetingServiceTest {
private lateinit var greetingService: GreetingService
@Mock
lateinit var timeService: TimeService
@Before
fun setup() {
@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)
val toothpickModule = module {
bind<GreetingService>().toClass<GreetingServiceImpl>().singleton()
bind<TimeService>().toInstance(TimeServiceImpl())
bind<MessageData>().toInstance(MessageData())
}
@InjectConstructor
class GreetingServiceImpl(private val messageData: MessageData, private val timeService: TimeService) :
GreetingService {
class ToothpickApplication : Application() {
override fun onCreate() {
super.onCreate()
KTP.openRootScope().installModules(toothpickModule)
}
}
class MainActivity : AppCompatActivity() {
private val greetingService: GreetingService by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
KTP.openRootScope().inject(this)
@RunWith(MockitoJUnitRunner::class)
class GreetingServiceMockTest {
@get:Rule
var toothPickRule = ToothPickRule(this, "scope")
@Inject
lateinit var greetingService: GreetingService
@Mock