import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class CounterViewModel : ViewModel() {
private val _counter = MutableLiveData<Int>(0)
val counter: LiveData<Int> = _counter
fun increment() {
val current = _counter.value ?: 0
_counter.value = current + 1
}
}
// Test file
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
class CounterViewModelTest {
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()
private lateinit var viewModel: CounterViewModel
private lateinit var observer: Observer<Int>
@Before
fun setup() {
viewModel = CounterViewModel()
observer = mock(Observer::class.java) as Observer<Int>
viewModel.counter.observeForever(observer)
}
@Test
fun initialCounterIsZero() {
assertEquals(0, viewModel.counter.value)
}
@Test
fun incrementIncreasesCounter() {
viewModel.increment()
assertEquals(1, viewModel.counter.value)
viewModel.increment()
assertEquals(2, viewModel.counter.value)
}
}This ViewModel holds a counter as LiveData starting at 0. The increment() function increases the counter by 1 safely handling null values. The unit test uses InstantTaskExecutorRule to run LiveData synchronously. It observes the LiveData with a mocked observer to avoid leaks. The tests check the initial value is zero and that calling increment() updates the counter correctly.