【问题标题】:Exception in thread "main @coroutine#2" java.lang.NullPointerException in ViewModelTest?ViewModelTest 中的线程“main @coroutine#2”java.lang.NullPointerException 中的异常?
【发布时间】:2021-06-24 09:30:47
【问题描述】:

我已经在 ViewModel 中使用带有 mockito 的协程编写了单元测试。上课,但我得到以下异常

 Exception in thread "main @coroutine#2" java.lang.NullPointerException
    at com.example.giphyandroidapp.viewmodel.GiphyTaskViewModel$getGifsFromText$1.invokeSuspend(GiphyTaskViewModel.kt:24)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50)
    at kotlinx.coroutines.test.internal.TestMainDispatcher.dispatch(MainTestDispatcher.kt:35)
    at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:305)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:27)
    at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:110)
    at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:158)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56)
    at kotlinx.coroutines.BuildersKt.launch(Unknown Source)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default(Builders.common.kt:49)
    at kotlinx.coroutines.BuildersKt.launch$default(Unknown Source)
    at com.example.giphyandroidapp.viewmodel.GiphyTaskViewModel.getGifsFromText(GiphyTaskViewModel.kt:22)
    at com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest$onCreation_fetchUserApiCalled_dataSavedToLiveData$1.invokeSuspend(GiphyTaskViewModelTest.kt:61)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:274)
    at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:84)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:59)
    at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:38)
    at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
    at com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest.onCreation_fetchUserApiCalled_dataSavedToLiveData(GiphyTaskViewModelTest.kt:57)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:54)
    at com.example.giphyandroidapp.viewmodel.TestCoroutineRule$apply$1.evaluate(TaskCoroutineRule.kt:22)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:99)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:105)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:40)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:42)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:72)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)


java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.

    at android.os.Looper.getMainLooper(Looper.java)
    at androidx.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:77)
    at androidx.arch.core.executor.ArchTaskExecutor.isMainThread(ArchTaskExecutor.java:116)
    at androidx.lifecycle.LiveData.assertMainThread(LiveData.java:486)
    at androidx.lifecycle.LiveData.observeForever(LiveData.java:224)
    at com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest$onCreation_fetchUserApiCalled_dataSavedToLiveData$1.invokeSuspend(GiphyTaskViewModelTest.kt:63)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:274)
    at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:84)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:59)
    at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:38)
    at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
    at com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest.onCreation_fetchUserApiCalled_dataSavedToLiveData(GiphyTaskViewModelTest.kt:57)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:54)
    at com.example.giphyandroidapp.viewmodel.TestCoroutineRule$apply$1.evaluate(TaskCoroutineRule.kt:22)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:99)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:105)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:40)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:42)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:72)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

在我已实现视图模型逻辑的 ViewModel 类下方

 @HiltViewModel
class GiphyTaskViewModel
@Inject
constructor(private val giphyTaskRepository: GiphyTaskRepository):ViewModel()
{
    var giphyresponse = MutableLiveData<Result<List<DataItem>?>>()



    fun getGifsFromText(apikey:String,text:String,limit:Int)= viewModelScope.launch {
        giphyTaskRepository.getGifsFromText(apikey,text,limit).let { response->
            if(response?.isSuccessful){
                var list=response.body()?.data
                giphyresponse.postValue(Success(list))
            }else{
                Error(Exception(response.message()))

            }

        }
    }

}

在存储库类下

class GiphyTaskRepository
@Inject
constructor(private val giphyTaskApiService: GiphyTaskApiService)
{

    suspend fun getGifsFromText(apikey:String,text:String,limit:Int)=
        giphyTaskApiService.getGifsFromText(apikey,text,limit)
}

接口类下面

接口 GiphyTaskApiService {

    @GET("gifs/search")
    suspend fun getGifsFromText(
        @Query("api_key") api_key:String,
        @Query("q") q:String ,
        @Query("limit") limit:Int
    ):Response<GiphyResponse>
}

在我的 ViewModel 测试类下面

 @ExperimentalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class GiphyTaskViewModelTest {







    @Mock
    private lateinit var apiUsersObserver: Observer<Result<List<DataItem>?>>


    @RegisterExtension
    @JvmField
    @get:Rule
    val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule()

    @get:Rule
   val testCoroutineRule = TestCoroutineRule()
    @Mock
     var giphyTaskViewModel:GiphyTaskViewModel? = null

    @Mock
     lateinit var  giphyTaskRepository:GiphyTaskRepository








    @Before
     fun setUp() {


        /* Create a mock response */;
        /* Create a mock response */;


                giphyTaskViewModel = GiphyTaskViewModel(giphyTaskRepository)
        }

    @Test
    fun onCreation_fetchUserApiCalled_dataSavedToLiveData() {
        runBlockingTest {



            val response: Response<GiphyResponse> = mock()


            giphyTaskViewModel?.getGifsFromText(Constants.Api_Key,"text", Constants.Limit)
           `when`(giphyTaskRepository.getGifsFromText(Constants.Api_Key,"text", Constants.Limit)).thenReturn(response)
            giphyTaskViewModel?.giphyresponse?.observeForever(apiUsersObserver)
            assertNotNull(giphyTaskViewModel?.giphyresponse?.value)




        }
    }



}

我尝试过的

1.[我已尝试以下链接][1]

  1. 我已重写 Viewmodel 逻辑,但出现以下异常 线程“main @coroutine#2”中的异常 java.lang.NullPointerException 在 com.example.giphyandroidapp.viewmodel.GiphyTaskViewModel$getGifsFromText$1.invokeSuspend(GiphyTaskViewModel.kt:26) 在 kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) 在 kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106) 在 kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50) 在 kotlinx.coroutines.test.internal.TestMainDispatcher.dispatch(MainTestDispatcher.kt:35) 在 kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:305) 在 kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30) 在 kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:27) 在 kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:110) 在 kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:158) 在 kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56) 在 kotlinx.coroutines.BuildersKt.launch(未知来源) 在 kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default(Builders.common.kt:49) 在 kotlinx.coroutines.BuildersKt.launch$default(未知来源) 在 com.example.giphyandroidapp.viewmodel.GiphyTaskViewModel.getGifsFromText(GiphyTaskViewModel.kt:24) 在 com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest$onCreation_fetchUserApiCalled_dataSavedToLiveData$1.invokeSuspend(GiphyTaskViewModelTest.kt:82) 在 com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest$onCreation_fetchUserApiCalled_dataSavedToLiveData$1.invoke(GiphyTaskViewModelTest.kt) 在 com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest$onCreation_fetchUserApiCalled_dataSavedToLiveData$1.invoke(GiphyTaskViewModelTest.kt) 在 kotlinx.coroutines.test.TestBuildersKt$runBlockingTest$deferred$1.invokeSuspend(TestBuilders.kt:50) 在 kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) 在 kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106) 在 kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50) 在 kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:305) 在 kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30) 在 kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:27) 在 kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:110) 在 kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:158) 在 kotlinx.coroutines.BuildersKt__Builders_commonKt.async(Builders.common.kt:91) 在 kotlinx.coroutines.BuildersKt.async(未知来源) 在 kotlinx.coroutines.BuildersKt__Builders_commonKt.async$default(Builders.common.kt:84) 在 kotlinx.coroutines.BuildersKt.async$default(未知来源) 在 kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:49) 在 kotlinx.coroutines.test.TestBuildersKt.runBlockingTest$default(TestBuilders.kt:45) 在 com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest.onCreation_fetchUserApiCalled_dataSavedToLiveData(GiphyTaskViewModelTest.kt:75) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.base/java.lang.reflect.Method.invoke(Method.java:566) 在 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59) 在 org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 在 org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56) 在 org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 在 org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) 在 org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:54) 在 com.example.giphyandroidapp.viewmodel.TestCoroutineRule$apply$1.evaluate(TaskCoroutineRule.kt:22) 在 org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) 在 org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100) 在 org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366) 在 org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103) 在 org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63) 在 org.junit.runners.ParentRunner$4.run(ParentRunner.java:331) 在 org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79) 在 org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329) 在 org.junit.runners.ParentRunner.access 100 美元(ParentRunner.java:66) 在 org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293) 在 org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) 在 org.junit.runners.ParentRunner.run(ParentRunner.java:413) 在 org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:99) 在 org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:105) 在 org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:40) 在 org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163) 在 org.junit.runner.JUnitCore.run(JUnitCore.java:137) 在 com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69) 在 com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33) 在 com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220) 在 com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

java.lang.NullPointerException 在 androidx.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:77) 在 androidx.arch.core.executor.ArchTaskExecutor.isMainThread(ArchTaskExecutor.java:116) 在 androidx.lifecycle.LiveData.assertMainThread(LiveData.java:486) 在 androidx.lifecycle.LiveData.observeForever(LiveData.java:224) 在 com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest$onCreation_fetchUserApiCalled_dataSavedToLiveData$1.invokeSuspend(GiphyTaskViewModelTest.kt:84) 在 com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest$onCreation_fetchUserApiCalled_dataSavedToLiveData$1.invoke(GiphyTaskViewModelTest.kt) 在 com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest$onCreation_fetchUserApiCalled_dataSavedToLiveData$1.invoke(GiphyTaskViewModelTest.kt) 在 kotlinx.coroutines.test.TestBuildersKt$runBlockingTest$deferred$1.invokeSuspend(TestBuilders.kt:50) 在 kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) 在 kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106) 在 kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50) 在 kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:305) 在 kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30) 在 kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:27) 在 kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:110) 在 kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:158) 在 kotlinx.coroutines.BuildersKt__Builders_commonKt.async(Builders.common.kt:91) 在 kotlinx.coroutines.BuildersKt.async(未知来源) 在 kotlinx.coroutines.BuildersKt__Builders_commonKt.async$default(Builders.common.kt:84) 在 kotlinx.coroutines.BuildersKt.async$default(未知来源) 在 kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:49) 在 kotlinx.coroutines.test.TestBuildersKt.runBlockingTest$default(TestBuilders.kt:45) 在 com.example.giphyandroidapp.viewmodel.GiphyTaskViewModelTest.onCreation_fetchUserApiCalled_dataSavedToLiveData(GiphyTaskViewModelTest.kt:75) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.base/java.lang.reflect.Method.invoke(Method.java:566) 在 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59) 在 org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 在 org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56) 在 org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 在 org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) 在 org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:54) 在 com.example.giphyandroidapp.viewmodel.TestCoroutineRule$apply$1.evaluate(TaskCoroutineRule.kt:22) 在 org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) 在 org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100) 在 org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366) 在 org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103) 在 org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63) 在 org.junit.runners.ParentRunner$4.run(ParentRunner.java:331) 在 org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79) 在 org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329) 在 org.junit.runners.ParentRunner.access 100 美元(ParentRunner.java:66) 在 org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293) 在 org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) 在 org.junit.runners.ParentRunner.run(ParentRunner.java:413) 在 org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:99) 在 org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:105) 在 org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:40) 在 org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163) 在 org.junit.runner.JUnitCore.run(JUnitCore.java:137) 在 com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69) 在 com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33) 在 com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220) 在 com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

我想知道我到底在哪里犯了错误,我必须怎样才能成功通过测试

【问题讨论】:

  • 如果我没记错的话,这不会改变您在空对象上调用方法的事实,giphyTaskRepository。我猜MockitoJUnitRunner 没有检测到您的lateinit 字段。我之前没有将 Mockito 与 Kotlin 结合使用,所以我不能确定
  • @Jeroen Steenbeeke 那么你的建议是什么
  • 我认为如果你检查其他地方我也迟到了字段,情况并非如此
  • @Before 方法中设置断点并检查字段值?可能只是 Mockito 直到这些运行之后才设置它们。同样,我之前没有在 Kotlin 中使用过 Mockito,所以我现在猜测(因此我发表评论而不是发布答案)

标签: android kotlin junit kotlin-coroutines mockito-kotlin


【解决方案1】:

我认为正在发生的事情是,您的 GiphyTaskRepository 的模拟版本表现出默认的 Mockito 行为,即为所有没有明确指定行为的方法返回 null

因此,您在GiphyTaskViewModel 中的调用giphyTaskRepository.getGifsFromText(apikey,text,limit) 返回null,导致随后对let 的调用抛出NullPointerException。

为避免这种情况,您需要明确指定此方法应返回的内容,例如在您的 setUp 方法中:

@Before
fun setUp() {
  val response: Response<GiphyResponse> = /* Create a mock response */;
  when(giphyTaskRepository.getGifsFromText(any(),any(),any())).thenReturn(response);

  giphyTaskViewModel = GiphyTaskViewModel(giphyTaskRepository)
}

但是,由于您使用的是协程,所以它变得有点棘手。您应该包含mockito-kotlin 库:

testImplementation "org.mockito.kotlin:mockito-kotlin:x.x.x"

接下来,GiphyTaskRepository 和方法 getGifsFromText 都需要声明为 open 才能使模拟工作。

最后,你需要稍微改变一下存根:

@Before
fun setUp() = runBlocking { // This bit is important
  val response: Response<GiphyResponse> = /* Create a mock response */;
  given(giphyTaskRepository.getGifsFromText(any(),any(),any())).willSuspendableAnswer {
                response
            }
  giphyTaskViewModel = GiphyTaskViewModel(giphyTaskRepository)

  Unit 
}

我相信你的测试方法会成功

【讨论】:

  • 但是 when(giphyTaskRepository.getGifsFromText(any(),any(),any())).thenReturn(response) 只能用在 fun onCreation_fetchUserApiCalled_dataSavedToLiveData()
  • 随你喜欢。 when 语句可以放在 setup 方法中,也可以放在 test 方法中
  • 是的,但我会调用该方法,我收到以下错误警告暂停函数“getGifsFromText”只能从协程或其他暂停函数中调用
  • 我明白了。看来您需要做一些额外的工作才能将模拟与协程一起使用:github.com/mockito/mockito-kotlin/pull/357
  • 你能推荐其他方法吗
猜你喜欢
  • 2018-10-15
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 2023-03-10
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多