Skip to content

Checking if the function call in the view model is invoked

Devrath edited this page Jun 26, 2021 · 1 revision

Use case for this implementation

  • We usually come across a scenario where we are using a service.
  • Consider this service as an analytics service for example, that logs some message to the analytics server.
  • Now this service is passed as a reference for a view model.
  • Using this reference, we are invoking a method of that service.
  • Objective of the scenario is we cant to check that if this log event is triggered when the ViewModel is invoked and its function is called.

viewModel class

class ImagesViewModel(
  private val imageListProvider: ImageListProvider,
  private val analytics: SpacingAnalytics
)
  : ViewModel() {

  val imageLiveData = MutableLiveData<List<ApodImage>>()
  val errorLiveData = MutableLiveData<String>()

  init {
    viewModelScope.launch {
      try {
        analytics.logEvent("Fetching images")
        val items = imageListProvider.buildImageList().filter { it.media_type == "image" }
        imageLiveData.value = items
      } catch (exception: Exception) {
        errorLiveData.value = exception.message
      }
    }
  }
}

SpacingAnalytics service

class SpacingAnalytics {
  fun logEvent(event: String, attributes: Map<String, String> = emptyMap()) {
    val newAttribtues = attributes.toMutableMap()
    newAttribtues["client_type"] = "Android"
    newAttribtues["version"] = "1"
    ThirdPartyAnalyticsProvider.logEvent(event, newAttribtues)
  }
}

Test function

@Test
fun `check if the fetching images event is logged in analytics`() {
   val imageListProvider = mockk<ImageListProvider>()
   val spacingAnalytics = mockk<SpacingAnalytics>()

   // -----------------------------------------> SUT
   ImagesViewModel(imageListProvider,spacingAnalytics)
   // Fetching images is present in the init block so once the constructor is initiated the function is called

   //Now we need to check if the method is called inside
   every { spacingAnalytics.logEvent("Fetching the images") } just Runs
}
Clone this wiki locally