[英]How to test Hive delete function on Flutter?
我用 HiveDB 进行了这个测试,应该调用 function 中的“删除”方法,但它没有通过,它直接进入“onFavoritePress”function 的“put”,我做错了什么?
测试:
void main() {
late int index;
late MockBox box;
late HandleFavoriteImpl sut;
setUp(() {
index = faker.randomGenerator.integer(10);
box = MockBox();
box.put(index, index);
sut = HandleFavoriteImpl(box);
});
test('Should call delete when the value already exists', () async {
sut.onFavoritePress(index);
verify(box.delete(index)).called(1);
});
}
被测物:
class HandleFavoriteImpl {
final Box favoritesBox;
HandleFavoriteImpl(this.favoritesBox);
void onFavoritePress(int index) {
if (favoritesBox.containsKey(index)) {
favoritesBox.delete(index);
return;
}
favoritesBox.put(index, index);
}
}
错误:
No matching calls. All calls: MockBox<dynamic>.put(2, 2), MockBox<dynamic>.containsKey(2), MockBox<dynamic>.put(2, 2)
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
我将向您解释为什么测试没有通过,并为您提供一种方法来检查是否从Hive
框中删除了一个项目。
Hive
库方法,例如delete()
、 put()
、 deleteAt()
...,是异步的 ( Future<void>
),因此调用它们即使看起来很快,也需要一些时间来解决,因此请尝试以下代码:
// ...
if (favoritesBox.containsKey(index)) {
favoritesBox.delete(index);
return;
}
在delete()
方法得到解决之前不会await
,因此它将被执行并立即从 function return
,留下元素未从您的Hive
框中删除(尚未)的标记,您只需要等待它直到它以await
结束然后从 function return
,所以尝试这段代码就可以做到:
Future<void> onFavoritePress(int index) async {
if (favoritesBox.containsKey(index)) {
await favoritesBox.delete(index);
return;
}
favoritesBox.put(index, index);
}
现在,第二件事,关于知道 object 是否从Hive
框中删除,您需要将元素包装在自定义 class 中,这需要扩展HiveObject
:
@HiveType()
class Example extends HiveObject {
@HiveField(0)
int index;
}
然后为它生成一个适配器,请参考这个,
然后使用以下命令注册该适配器:
Hive.registerAdapter(GeneratedAdapter());
然后,您需要打开一个类型为 class 的盒子:
await Hive.openBox<Example>();
然后您将有权访问isInBox
属性,该属性检查分配给它的Hive
框中存在的元素,作为验证元素是否已删除的示例:
final example = Example();
example.index = 10;
await yourBox.put(example);
example.isInBox; // true
await yourBox.delete(example);
example.isInBox; // false
只需考虑这些方法是Future<void>
,忘记await
将导致立即执行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.