扩展LiveData的模拟类

时间:2017-11-07 17:38:34

标签: android unit-testing android-architecture-components android-livedata

我想对依赖于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);
}

}

0 个答案:

没有答案