【发布时间】:2019-08-05 10:42:16
【问题描述】:
我开始学习如何编写测试并编写这个来测试我的api:
class SharedViewModelTest {
@get:Rule
val rule = InstantTaskExecutorRule()
@Mock private lateinit var networkHelper: NetworkHelperImpl
@Mock private lateinit var employeeInteractor: EmployeeInteractorImpl
@Mock private lateinit var specialityInteractor: SpecialityInteractorImpl
@Mock private lateinit var api:ApiService
private lateinit var sharedViewModel: SharedViewModel
@Before fun setUp() {
MockitoAnnotations.initMocks(this)
sharedViewModel = SharedViewModel(networkHelper, employeeInteractor, specialityInteractor)
}
@Test
fun `check is json correct`(){
val result = runBlocking { api.loadData().await().items }
result shouldNotBe null
result.size shouldNotBe 0
}
}
但是当我尝试运行 check is json correct 时我有这个:
java.lang.NullPointerException
at com.example.testtask.view.viewmodel.SharedViewModelTest$check is json correct$result$1.invokeSuspend(SharedViewModelTest.kt:38)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:233)
at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.kt:116)
at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:76)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:53)
at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:35)
at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
at com.example.testtask.view.viewmodel.SharedViewModelTest.check is json correct(SharedViewModelTest.kt:38)
我真的无法理解为什么我有 NPE(不是服务器线程错误,NPE 完全正确)。我评论了我比较结果的行,但它仍然很糟糕,所以我认为这不是关于响应,而是其他的东西。
谁能给我解释一下?
我认为应用级别的 gradle 依赖可以提供帮助:
//Tests
testImplementation 'junit:junit:4.13-beta-3'
testImplementation "org.mockito:mockito-inline:2.8.47"
testImplementation 'org.robolectric:robolectric:4.3'
testImplementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.41'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit:1.3.41'
testImplementation "com.nhaarman:mockito-kotlin:1.4.0"
testImplementation 'org.amshove.kluent:kluent:1.14'
testImplementation 'android.arch.core:core-testing:1.1.1'
【问题讨论】:
标签: android unit-testing kotlin junit