Android Unit Test -> Problems mocking a method that has static class

Asked

Viewed 28 times

0

I am doing unit tests of my Viewmodel and have a method that saves the data in Firebase generating an id internally with the help of the Base64 class. In my class structure I call the viewModel.saveService method, which called the keyHash method responsible for instantiating my encryption class. in this case I am wanting to test the method viewModel.saveService() and I am having the following Exception on the line where I have the code -> whenever(servicesViewModel.setKeyHash(services.name)).thenReturn(hash) Exception :

org.mockito.exceptions.misusing.NullInsteadOfMockException: 
Argument passed to when() is null!
Example of correct stubbing:
    doThrow(new RuntimeException()).when(mock).someMethod();
Also, if you use @Mock annotation don't miss initMocks()

Test:

@Test
fun `Should save Service`() = runBlockingTest{
    val services = getSomeService()
    val hash = "oa69AWa3dw6aqa"

    mockkStatic(Base64::class)
    doNothing().whenever(Base64.encodeToString(any(), anyInt()))
    whenever(servicesViewModel.setKeyHash(services.name)).thenReturn(hash)

    servicesViewModel.saveService(services.name, services.description!!, services.cost!!, services.duration!!)

    verify(repository).saveService(services)

}

fun getSomeService() = Services("someId",
    "someName",
    "someDescription",
    "someCost",
    "someDurarion")

Viewmodel.kt

fun saveService(name: String?, description: String, cost: String, duration: String) = runBlocking (Dispatchers.IO){

    repository.saveService(Services(
        id = setKeyHash(name),
        name = name,
        description = description,
        cost = cost,
        duration = duration))
}

fun setKeyHash(s: String?): String{
    val hash = HashGenerator()
    return hash.encript(s!!)
}

Hashclass

class HashGenerator {

fun encript(text: String): String {
    return Base64.encodeToString(text.toByteArray(),
        Base64.DEFAULT).replace("(\\n|\\r)".toRegex(),
        "")
}

}
  • ever tried with powermockito?

  • yes, I followed some tutorials and they continue to block in the Base64 class.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.