LiveData的Android测试

问题描述 投票:6回答:1

我有这个模拟课:

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

android android-testing android-livedata
1个回答
14
投票

你可以不用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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.