我有这个模拟课:
class MockCategoriesRepository implements CategoriesRepository {
@Override
public LiveData<List<Category>> getAllCategories() {
List<Category> categories = new ArrayList<>();
categories.add(new Category());
categories.add(new Category());
categories.add(new Category());
MutableLiveData<List<Category>> liveData = new MutableLiveData<>();
liveData.setValue(categories);
return liveData;
}
}
和测试:
@Test
public void getAllCategories() {
CategoriesRepository categoriesRepository = new MockCategoriesRepository();
LiveData<List<Category>> allCategories = categoriesRepository.getAllCategories();
}
我想测试List<Category>
为空。
我该怎么做?我可以使用Mockito吗?
你可以不用Mockito,只需在测试中添加以下行:
Assert.assertFalse(allCategories.getValue().isEmpty());
为了使它工作,你还应该添加:
testImplementation "android.arch.core:core-testing:1.1.1"
到你的app/build.gradle
文件,并将以下内容添加到测试类:
@Rule
public TestRule rule = new InstantTaskExecutorRule();
这是必需的,因为默认情况下,LiveData
在自己的线程上运行,该线程来自Android依赖(在纯JVM环境中不可用)。
所以,整个测试看起来应该是这样的:
public class ExampleUnitTest {
@Rule
public TestRule rule = new InstantTaskExecutorRule();
@Test
public void getAllCategories() {
CategoriesRepository categoriesRepository = new MockCategoriesRepository();
LiveData<List<Category>> allCategories = categoriesRepository.getAllCategories();
Assert.assertFalse(allCategories.getValue().isEmpty());
}
}