安卓LiveData测试

11

我有这个模拟类:

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吗?

1个回答

23

您可以不使用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());
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接