Test case failing: ClassCastException: androidx.lifecycle.ViewModel$Subclass1 cannot be cast to class SecondChildViewModel

81 views Asked by At

Having parent and child Activities & viewModels. My assumption is always taking parent viewmodel and not able to take child viewModel. so that my test cases are failing.

viewModels are like

  • FirstSecondChildCancellationViewModel -> ParentViewModel
  • SecondChildCancellationViewModel -> ParentViewModel

Activities are as follows:

  • FirstChildCancellationActivity -> ParentActivity

  • SecondChildCancellationActivity -> ParentActivity

      @Before
      fun setUp() {
          binding = mockk()
          val intent = Intent()
          val bundle = Bundle()
          bundle.putParcelable(EXTRA_HEADER_LAYOUT, myCancelModel)
          intent.putExtras(bundle)
    
          subjectController = Robolectric.buildActivity(
              SecondChildCancellationActivity::class.java, intent
          ).create() // Test case failing, error pasted below
    
          subject = subjectController.get()
    
          mockkStatic(ViewModelProviders::class)
          val mockViewModelProvider = mockkClass(ViewModelProvider::class)
          every { ViewModelProviders.of(any<FragmentActivity>(), any()) } returns mockViewModelProvider
          every { mockViewModelProvider.get(any<Class<SecondChildCancellationViewModel>>()) } returns mockViewModel
    
      }
    

My Testcase:

    @Test
    fun `verify onCreate init is happening and status is displaying in header`() {

        subjectController.visible().get()

        assert(subject.cancelId).isEqualTo(myCancelModel.cancelId)
        assert(binding.statusTextView.status).isEqualTo(myCancelModel.statusText)
    }

Getting Error on my testcase:

    Caused by: java.lang.ClassCastException: class androidx.lifecycle.ViewModel$Subclass1 cannot be cast to class com.company.project.cancellation.SecondChildCancellationViewModel (androidx.lifecycle.ViewModel$Subclass1 and com.company.project.cancellation.SecondChildCancellationViewModel are in unnamed module of loader org.robolectric.internal.AndroidSandbox$SdkSandboxClassLoader @12e24679)
    at com.company.project.cancellation.SecondChildCancellationActivity.retrieveViewModel(SecondChildCancellationActivity.kt:47)
0

There are 0 answers