0

我想对依赖于 LocationLiveData 类的存储库进行单元测试:

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;
        ...     
    }
    ...
}

在我调用 setValue(someLocationDataInstance) 之后,如何使模拟像 liveData 一样发出 LocationData 对象?

@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));
    }
}

更新 1:我想测试以下存储库:

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);
}

}

4

0 回答 0