Skip to content

Instantly share code, notes, and snippets.

View duyp's full-sized avatar

Duy Pham duyp

View GitHub Profile
abstract class Bird {
...
abstract fun fly()
}
class Penguin: Bird() {
...
override fun fly() {
throw Exception("Can't fly!")
}
// domain
sealed class ErrorEntity {
sealed class ApiError: ErrorEntity() {
// .....
}
sealed class FileError: ErrorEntity() {
object NotFound: FileError()
abstract class OnOneClickListener(private val minClickInterval: Long = 500) : View.OnClickListener {
private var lastClickedTime: Long? = null
override fun onClick(v: View) {
val currentTime = SystemClock.elapsedRealtime()
if(lastClickedTime == null || currentTime - lastClickedTime!! > minClickInterval) {
onOneClick(v)
}
}
package ch.immoscout24.ImmoScout24
import androidx.lifecycle.Observer
/**
* Used for testing [androidx.lifecycle.LiveData]
*
* @param <T> type of data
*/
@Suppress("unused")
private val usecase: TestUseCase = Mockito.mock(TestUseCase::class.java)
private val viewModel = ScreenViewModel(usecase)
private lateinit var stateObserver: LiveDataTestObserver<ScreenState>
@Before
fun setup() {
stateObserver = LiveDataTestObserver()
viewModel.liveData.observeForever(stateObserver) // start observing live data
class LiveDataTestObserver<T> : Observer<T> {
private val values: MutableList<T> = ArrayList()
override fun onChanged(value: T?) {
// whenever new value is set, add it into value list
value?.let { values.add(value) }
}
/**
@Test
fun `click button - success - should show loading then success message`() {
Mockito.`when`(usecase.execute()).thenReturn(Completable.complete())
viewModel.clickButton()
// todo how to verify the state was turned into loading before showing the success message?
// verify last state
viewModel.liveData.value!!.apply {
assertFalse(isLoading)
class ScreenViewModel: ViewModel() {
private val mutableLiveData = MutableLiveData<Int>()
val liveData: LiveData<Int> = mutableLiveData
fun clickButton() {
mutableLiveData.value = (mutableLiveData.value ?: 0) + 1
}
}
data class ScreenState(
val isLoading: Boolean,
val isButtonEnabled: Boolean,
val message: String?
)
class ScreenViewModel(private val usecase: TestUseCase): ViewModel() {
private val disposable = CompositeDisposable()
class ComponentA
class ComponentB(val a: ComponentA)
class MyTest : KoinTest {
// Lazy inject property
val componentB : ComponentB by inject()
@Test
fun `should inject my components`() {