如何解决使用 Mockito Flutter 模拟 Hive
所以基本上,当我想存储一些东西时,我想检查我是否已经传递了我需要传递给 HiveInterface
和 Box
的任何东西。
test.dart
:
group('cacheStoraygeUser',() {
test(
'should call HiveInterface and Box to cache data',() async {
when(mockHiveInterface.openBox(any)).thenAnswer((_) async => mockBox);
when(mockBox.put(0,tStoraygeusermodel))
.thenAnswer((_) async => tStoraygeusermodel);
// act
dataSourceImpl.cacheStoraygeUser(tStoraygeusermodel);
// assert
verify(mockHiveInterface.openBox(STORAYGE_USER_Box));
verify(mockBox.put(STORAYGE_USER_ENTRY,tStoraygeusermodel));
},);
});
我对 dataSourceImpl.cacheStoraygeUser()
的实现:
@override
Future<void> cacheStoraygeUser(
Storaygeusermodel storaygeusermodelToCache) async {
/// Precaution to ensure that [STORAYGE_USER_Box] has been opened.
///
/// If the Box,is in fact not opened,Hive will just return the Box since
/// the Box is a Singleton. I think.
final Box = await hiveInterface.openBox(STORAYGE_USER_Box);
Box.put(STORAYGE_USER_ENTRY,storaygeusermodelToCache);
}
当我尝试运行测试时,出现此错误:
type 'Null' is not a subtype of type 'Future<void>'
MockBox.put
package:hive/…/Box/Box_base.dart:80
我已经为 HiveInterface
和 Box
生成了模拟类。我认为如果我想测试 Hive,我应该这样做,因为我似乎无法为 Hive 本身生成 Mock 类。但是,如果您知道更好或更正确的解决方案,请告诉我。
我还编写了另一个用于从 Hive 获取内容的测试。这工作得很好。
test(
'should return StoraygeUser from StoraygeUserBox when there is one in the cache',() async {
// arrange
when(mockHiveInterface.openBox(any)).thenAnswer((_) async => mockBox);
when(mockBox.getAt(any)).thenAnswer((_) async => tStoraygeusermodel);
// act
final result = await dataSourceImpl.getCachedStoraygeUser();
// assert
verify(mockHiveInterface.openBox(any));
verify(mockBox.getAt(any));
expect(result,equals(tStoraygeusermodel));
},);
提前致谢!
解决方法
此问题已在 Mockito 5.0.9 中修复
问题源于 Box 实现 BoxBase 而不是 扩展 它。
旧版本的 Mockito 无法接受这一点,因此,在模拟类中不会生成 putAt 和 getAt 等方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。