我正在尝试使用Mockito模拟房间数据库,以便可以在存储库中测试复杂的算法。无论我朝哪个方向前进,我都会遇到很多不同的错误。
首先,我尝试仅模拟整个数据库对象,这创建了一个空接口异常。
为解决此问题,我使用了Room的静态对象生成器。 (这是一个仪器化的单元测试,因此我可以访问底层的Android依赖项)
class PartitioningCollector<T> implements Collector<T, List<List<T>>, List<List<T>>> {
private final int batchSize;
private final List<T> batch;
public PartitioningCollector(int batchSize) {
this.batchSize = batchSize;
this.batch = new ArrayList<>(batchSize);
}
@Override
public Supplier<List<List<T>>> supplier() {
return LinkedList::new;
}
@Override
public BiConsumer<List<List<T>>, T> accumulator() {
return (total, element) -> {
batch.add(element);
if (batch.size() >= batchSize) {
total.add(new ArrayList<>(batch));
batch.clear();
}
};
}
@Override
public BinaryOperator<List<List<T>>> combiner() {
return (left, right) -> {
List<List<T>> result = new ArrayList<>();
result.addAll(left);
result.addAll(left);
return result;
};
}
@Override
public Function<List<List<T>>, List<List<T>>> finisher() {
return result -> {
if (!batch.isEmpty()) {
result.add(new ArrayList<>(batch));
batch.clear();
}
return result;
};
}
@Override
public Set<Characteristics> characteristics() {
return emptySet();
}
}
有了这个,我收到了误用的匹配器异常... ++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 在此处检测到错误或错误使用的参数匹配器:
com.example.barrechat108.RepositoryTests.doesReposRequestBounds(RepositoryTests.kt:138)上的-> -> com.example.barrechat108.RepositoryTests.doesReposRequestBounds(RepositoryTests.kt:138) -> com.example.barrechat108.RepositoryTests.doesReposRequestBounds(RepositoryTests.kt:139) -> com.example.barrechat108.RepositoryTests.doesReposRequestBounds(RepositoryTests.kt:139)`
您不能在验证或存根之外使用参数匹配器。 ++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++
答案 0 :(得分:1)
进行测试时,您可以将会议室数据库构造为内存数据库。因此,所有存储的内容将一直持续到该过程关闭为止。因此没有任何东西会持续存在,非常适合测试!
代码:
Room.inMemoryDatabaseBuilder(context, TestDatabase::class.java).build()
答案 1 :(得分:0)
我并不为解决方案感到骄傲,但是它可以工作。我没有将完整的数据库对象传递给我的Repository类的构造函数,而是创建了另一个直接使用dao的重写的构造函数。这样,我可以简单地模拟dao,而不必创建一些根本无法使用的奇怪的数据库功能链。