Search code examples
androidunit-testingkotlinmockitolocation

Android unit testing Location not mocked


I am trying to test my presenter and I need a mocked location, however, I get null or have default values such as 0.0 for lat, long, bearing and so on

I have already tried creating a new Location object and initializing all the fields I need.

    val latitude = 37.422
    val longitude = -122.084

    val mockLocation = mock(Location::class.java)
    mockLocation.latitude = latitude
    mockLocation.longitude = longitude

    presenter.loadsAirpots(latitude, longitude)
    presenter.locationChanged(mockLocation)

    System.out.println(mockLocation.latitude)

I expect latitude to be 37.422 but the actual output is 0.0


Solution

  • When you mock an object the real implementation won't be called. You are trying to call setLatitude(latitude) but it won't change the value.

    If you want to mock the object you should do:

    val mockLocation = mock(Location::class.java)
    given(mockLocation.getLatitude()).willReturn(latitude)
    given(mockLocation.getLongitude()).willReturn(longitude)
    

    Or you could create a real object:

    val realLocation = Location("provider")
    realLocation.latitude = latitude
    realLocation.longitude = longitude