2

We have a Configuration class and LocalStorage class Configuration takes LocalStorage instance in constructor, LocalStorage takes Context in constructor. We are just trying to start with UI testing. We are trying to do this

   private val localStorage = Mockito.mock(LocalStorage::class.java)

   // in our setup method
   Mockito.`when`(localStorage.getString(anyString())).thenReturn(str)

Here problem is that getString() method call starts happening immediately when tests are run. We have not even written actual test yet.

Mockito Android version: 3.1.0

Abhishek Bansal
  • 5,197
  • 4
  • 40
  • 69

3 Answers3

0

I think what problem is may be in Mock final Kotlin classes during UI tests. It is looks like what you use plugin for Mockito to "open" classes.

Possible solutions:

  1. Make LocalStorage to be interface, not class. (5th principle of SOLID, abstraction/realisation). Your problem may disappear because interfaces are open by their nature.
  2. Use Mockk library to mock your LocalStorage and other classes. This framework is better for Kotlin.
Peter Staranchuk
  • 1,343
  • 3
  • 14
  • 29
0

Have you considered using alternative approach?

doReturn(str).when(localStorage).getString(anyString())

(import needed: import org.mockito.Mockito.doReturn)

ror
  • 3,295
  • 1
  • 19
  • 27
0

Problem was this LocalStorage was being initialized by our Application class. Mock fails when a dependency is already initialized before. Solution is to create a TestApplication with CustomAndroidJUnitRunner. Make sure dependencies are not pre-initialised and only initialise dependencies as per respective test's requirenment.

Abhishek Bansal
  • 5,197
  • 4
  • 40
  • 69