我找不到能帮助我测试ViewModel
的解决方案。我一直在读,添加规则就足够了:
@get:Rule
var rule: TestRule = InstantTaskExecutorRule()
但我不断得到:
java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
我的测试类现在看起来像这样:
@RunWith(MockitoJUnitRunner::class)
class MainActivityViewModelTest {
@get:Rule
val taskExecutorRule = InstantTaskExecutorRule()
val weatherProviderMock = mock<WeatherProvider>()
val sut = MainActivityViewModel(weatherProviderMock, mock(), mock(), mock())
@Test
fun shouldPass() {
assertTrue(true)
}
}
我的应用程序build.gradle中也包含以下内容:
testImplementation 'junit:junit:4.12'
testImplementation "android.arch.core:core-testing:1.1.1"
testImplementation 'org.mockito:mockito-core:2.22.0'
testImplementation 'org.assertj:assertj-core:3.9.1'
testImplementation 'com.nhaarman:mockito-kotlin:1.6.0'
testImplementation 'org.mockito:mockito-inline:2.22.0'
任何帮助,不胜感激。
@Chris
能否请您告诉我下面的代码是否有问题(根据您建议的解决方案):
lateinit var sut: SummaryViewModel
@get:Rule
val rule: TestRule = InstantTaskExecutorRule()
@Before
fun setUp() {
sut = SummaryViewModel(calculatorMock, mock(), mock(), mock(), providerMock, mock())
}
@Test
fun `live data test`() {
val someLiveData = sut.someLiveDataValue
assertThat(true).isTrue()
}
答案 0 :(得分:0)
您可以使用Kotlin delegates惰性地初始化ViewModel
:
val viewModel by lazy {
MainActivityViewModel(weatherProviderMock, mock(), mock()...)
}