- 首先,在build.gradle文件中添加以下依赖项:
def paging_version = "3.0.0-alpha04"
implementation "androidx.paging:paging-runtime:$paging_version"
testImplementation "androidx.paging:paging-common:$paging_version"
- 然后,在要测试的类中创建Mock数据和Mockito对象:
@Mock
private MyAppDatabase mockDatabase;
@Mock
private MyDao mockDao;
private MyRepository repository;
private static final List MY_ENTITY_LIST = Arrays.asList(
new MyEntity(1, "A"),
new MyEntity(2, "B"),
new MyEntity(3, "C"),
new MyEntity(4, "D"),
new MyEntity(5, "E"),
new MyEntity(6, "F"),
new MyEntity(7, "G"),
new MyEntity(8, "H"),
new MyEntity(9, "I"),
new MyEntity(10, "J")
);
- 创建测试用的MockMyDataSource类,模拟DataSource类型:
class MockMyDataSource extends MyDataSource {
MockMyDataSource() {
super(mockDao);
}
@Override
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback callback) {
callback.onResult(MY_ENTITY_LIST, null, null);
}
@Override
public void loadAfter(@NonNull LoadParams params, @NonNull LoadCallback callback) {
callback.onResult(Collections.emptyList(), null);
}
@Override
public void loadBefore(@NonNull LoadParams params, @NonNull LoadCallback callback) {
// Do nothing
}
}
- 编写测试用例:
@Test
fun `paging test`() {
val mockPagingData = MockPagingData.from(MY_ENTITY_LIST)
`when`(mockDatabase.myDao()).thenReturn(mockDao)
`when`(mockDao.getMyEntities()).thenReturn(mockPagingData)
val dataSourceFactory = MyDataSourceFactory(mockDao)
val config = PagedList.Config.Builder()