gpt4 book ai didi

LiveData 的 Android 测试

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:27:05 24 4
gpt4 key购买 nike

我有这个模拟课:

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());
}
}

关于LiveData 的 Android 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48186432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com