首页 > 解决方案 > 当我用 Kotlin 测试 Retrofit API 时的 NPE

问题描述

我开始学习如何编写测试并编写这个来测试我的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 exacly)。我评论了我比较结果的行,但它仍然很糟糕,所以我认为这不是关于响应,而是其他的东西。

有人可以向我解释一下吗?

我认为应用程序级别的 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'

标签: androidunit-testingkotlinjunit

解决方案


您必须先模拟您的 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
    }

推荐阅读