I want to unit test a repository which depends on LocationLiveData class:
public class LocationLiveData extends LiveData<LocationData> {
private Context mContext;
private LocationCallback locationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
...
setValue(locationData);
}
};
@Inject
public LocationLiveData(Context context) {
mContext = context;
...
}
...
}
How can I make the mock act like liveData which emits a LocationData object after I called setValue(someLocationDataInstance)?
@RunWith(JUnit4.class)
public class LocationRepoImplTest {
@Rule
public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule();
private LocationRepo mLocationRepo;
private LocationLiveData mlocationLiveData;
@Before
public void setUp() throws Exception {
mlocationLiveData = mock(LocationLiveData.class);//(LocationLiveData) new MutableLiveData<LocationData>();
mLocationRepo = new LocationRepoImpl(mlocationLiveData);
}
@Test
public void getUserPosition() throws Exception {
LiveData<LatLng> result = mLocationRepo.getUserPosition();
Observer observer = mock(Observer.class);
result.observeForever(observer);
//how can I setValue for mLocationLiveData here?
//e.g this way: mLocationLiveData.setValue(new LocationData(TestUtil.posUser, (float) 10.0));
assertThat(result.getValue(), is(TestUtil.posUser));
}
}
Update 1: I want to test following repository:
public class LocationRepoImpl implements LocationRepo {
private LocationLiveData mLocationLiveData;
@Inject
public LocationRepoImpl(LocationLiveData locationLiveData) {
mLocationLiveData = locationLiveData;
}
@Override
public LiveData<LatLng> getUserPosition() {
return Transformations.map(mLocationLiveData, LocationData::getLatLng);
}
}