Reputation: 24318
I have been using Robolectric quite successfully up until now. I have an activity that gets the location manager. Now according to the documentation the robolectric framework incorporates a shadow class called "ShadowLocationManager" to make a kind of mock.
My question really is, how can I control this mock, can I control what will be returned? If so how?
Or do I have to create my "OWN" shadow class and implement "ShadowLocationManager".
I have been searching for documentation but I just can't find anything to confirm what I am asking.
If robolectric does contain a shadow for location manager how do I control what providers are enabled? I didn't want to implement my own shadow class if one already exists and can be configured and controlled.
Upvotes: 4
Views: 2572
Reputation: 33930
The shadow classes in Robolectric are substitutes of the various Android classes and can only be changed depending on their implemented functionality.
Looking at the source for ShadowLocationManager, you have some methods you can use to tweak the behavior of the fake:
public void setProviderEnabled(String provider, boolean isEnabled);
public void setProviderEnabled(String provider, boolean isEnabled, List<Criteria> criteria);
public boolean setBestProvider(String provider, boolean enabled);
public boolean setBestProvider(String provider, boolean enabled, List<Criteria> criteria);
public void setLastKnownLocation(String provider, Location location);
You can get the shadow instance for LocationManager with:
LocationManager instanceOfLocationManager = Robolectric.newInstanceOf(LocationManager.class);
ShadowLocationManager slm = Robolectric.shadowOf(instanceOfLocationManager);
Note: in the example I'm using Robolectric to create the instance of LocationManager
. Depending on your test setup, this instance might come from your injection framework or directly from calling Context.getSystemService(..)
. Bottom line is, make sure the instance in your test is the same instance used by the code that is being tested.
Upvotes: 5