ViewModelTest 中线程“main @coroutine#2”java.lang.NullPointerException 中出现异常?

2024-04-03

我已经在 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”中的 xception 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(本机方法) 在 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(本机方法) 在 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表现出返回的默认 Mockito 行为null对于所有没有明确指定行为的方法。

因此,您的电话giphyTaskRepository.getGifsFromText(apikey,text,limit) in GiphyTaskViewModel回报null,导致后续调用let抛出 NullPointerException。

为了避免这种情况,您需要显式指定此方法应返回什么,例如在您的setUp method:

@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 
}

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ViewModelTest 中线程“main @coroutine#2”java.lang.NullPointerException 中出现异常? 的相关文章

  • startActivity overridePendingTransition 只显示进入动画

    基本上 我遇到的问题是只显示输入幻灯片动画 调用 Activity 不会产生动画 startActivity intent overridePendingTransition R anim right in partly R anim le
  • 如何从一个活动中完成一系列开放的子活动?

    我正在尝试为我的应用程序制作一个退出按钮 无论如何 我能够跟踪我的应用程序中的所有活动实例 然后完成它们 但在某些情况下 仍有一些活动仍然存在 不知道怎么办 有没有什么方法可以杀死android中的特定应用程序 或者我可以通过任何其他方式退
  • 添加动态数据时 footable 出现问题

    我需要 jQuery Mobile 方面的一些帮助富表 http css tricks com footable a jquery plugin for responsive data tables 我正在表中动态添加数据 HTML tab
  • Android向后兼容技术

    我现在在开发基于最新 API 15 ICS 的 15 项活动 Android 应用程序方面取得了进展 现在我发现应用程序的主要功能主义者即使支持 android v4 也不向后兼容 例如 1 fragment事务动画 2 将StringSe
  • 有没有办法将搜索栏添加到我的实际首选项屏幕?

    我一直看到有关添加您自己的搜索栏首选项的教程 但它不在我实际的 prefs xml 中 有什么方法可以在我的主偏好设置屏幕中添加一个 或者我必须将其分开 Google 似乎有 2 个滑块首选项 搜索栏首选项 https github com
  • 编译后从字节代码中删除注释

    我们正在使用一个包含使用 JAXB 注释进行注释的 bean 的库 我们使用这些类的方式完全不依赖于 JAXB 换句话说 我们不需要 JAXB 也不依赖注释 但是 由于注释存在 它们最终会被处理注释的其他类引用 这要求我将 JAXB 捆绑到
  • 如何将 Android Instrumentation 测试推送到模拟器/设备?

    我正在尝试使用 Ubuntu 9 04 中的命令行 shell 在 Android 模拟器上运行 Webkit 布局测试 adb s emulator 5554 shell am instrument w com android dumpr
  • 维护 HttpUrlConnection 调用之间的会话(Native/Webview)

    让我从我做的开始desire 我想制作一个应用程序part native and part webviews Problem 维护本机和 webview 部分之间的会话 My 处理方法 this 我打算实现一个本机登录 其中我向用户展示两个
  • Android Facebook sdk 3.5 分享对话框

    您好 我正在为 android sdk 3 5 实现 facebook 共享对话框 但是我按照指南没有取得任何成功 FacebookDialog shareDialog new FacebookDialog ShareDialogBuild
  • Android ListView 自定义适配器 ImageButton

    这可能不是正确的方法 如果有更好的方法请告诉我 我创建了一个自定义适配器类 在我的 getView 方法中我膨胀了我想要使用的视图 public View getView int position View convertView View
  • 从 BroadcastReceiver 获取方法来更新 UI

    我正在尝试根据变量的变化更新用户界面BroadcastReceiver 因此 我需要调用一个扩展类的方法 以获取我提到的变量 BroadcastReceiver in MainActivity取决于但我无法以任何方式获得真正的返回值 扩展的
  • Android 谷歌地图 V2 已停止

    我正在尝试构建地图应用程序并关注这个链接 https blog emildesign rhcloud com p 435一步步 我在这里找到了类似的主题 但对我没有帮助 我想显示地图 但是当我运行它时 它返回强制关闭和我的 Android
  • 需要在 Android 中伪造正在扫描的 NFC 标签

    好的 我有一个应用程序 此应用程序仅在扫描 NFC 标签 任何标签 时才会完成任务 唯一的问题是 我没有任何 nfc 标签 无论如何 我正试图消除对卡的需要 所以我需要的是一种 伪造 使其看起来 就像已扫描 nfc 标签的方法 我可以编写应
  • 为本地@ExceptionHandler编写JUnit测试

    我有以下控制器 class Controller ResponseStatus HttpStatus OK RequestMapping value verifyCert method RequestMethod GET public vo
  • Android 消费品:“已经拥有该商品”,但 inventory.hasPurchase() 为 false

    我被 Google In App v3 困住了 我测试了一次没有消费的购买 例如 当应用程序在购买和消费之间崩溃时 现在我找不到出路 如果我尝试再次购买 它会显示 您已经拥有该商品 但是当我测试所有权时 它说我不拥有它 Inventory
  • 截图显示黑色

    我正在拍摄快照并创建缩略图 然后共享此图像 但缩略图显示全黑 我使用了以下代码 Bitmap bitmap View v1 v getRootView v1 setDrawingCacheEnabled true bitmap Bitmap
  • 在 android 中,第一次单击时按钮侦听器未注册

    因为我是 Android 新手 所以我遇到了按钮监听器的问题 我正在使用 OnClickListener 来处理胸像 但它第一次点击后不执行一旦我单击多个 它就会表现良好 但如何使其在第一次单击时成为可能 这是我的代码 public cla
  • 如何在 onDraw() 方法中定义与像素无关的高度

    我扩展了 View 来构建自定义小部件 我想用独立的像素单位定义小部件的高度 我认为可以通过将像素密度乘以所需的高度来完成 但我不知道该怎么做 到目前为止我所拥有的 最小化 public class Timeline extends Vie
  • 将 Crashlytics 集成到图书馆项目

    我有一个图书馆项目 自定义视图库项目 它没有任何活动 服务 我想将 Crashlytics SDK 集成到我的库中 当我尝试通过 Android Studio 的 Crashlytics 插件 工具栏中的图标 添加它时 它只是停留在 Che
  • 在android中使用BaseActivity的不同活动中的通用标头

    我想编写一次代码并在不同的活动中使用 我创建了一个Base Activity class为了那个原因 此外 不同活动中所有布局的标题都是相同的 我在以下人员的帮助下做到了这一点

随机推荐