我开始学习如何编写测试并编写此代码来测试我的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'
答案 0 :(得分:1)
您必须首先模拟api响应。例如:
@Test
fun `check is json correct`(){
val result = runBlocking {
whenever(api.loadData()).thenReturn(async {'create your data'})
api.loadData().await().items
}
result shouldNotBe null
result.size shouldNotBe 0
}