Flutter中Hive删除功能测试失败:未触发delete却执行put
HiveDB测试用例问题:预期触发delete操作却执行了put操作
我编写了HiveDB测试用例,预期触发HandleFavoriteImpl类onFavoritePress方法中的delete操作,但测试未通过,实际执行了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); }); }
实现代码(SUT)
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(...);`.)
问题原因
直接调用box.put(index, index)不会让MockBox的containsKey方法返回true——Mock作为模拟对象,默认不会记录你直接调用的put操作,所以onFavoritePress里的判断分支会走else,执行put操作。
修复方案
不要直接调用mock对象的put方法,而是通过mock框架设置containsKey的返回值,模拟数据已存在的场景:
修改后的测试代码:
void main() { late int index; late MockBox box; late HandleFavoriteImpl sut; setUp(() { index = faker.randomGenerator.integer(10); box = MockBox(); // 模拟containsKey返回true,代表该索引已存在 when(() => box.containsKey(index)).thenReturn(true); sut = HandleFavoriteImpl(box); }); test('Should call delete when the value already exists', () { sut.onFavoritePress(index); verify(box.delete(index)).called(1); // 额外验证不会执行put操作 verifyNever(box.put(index, index)); }); }
另外,测试方法不需要async,因为onFavoritePress是同步方法,可以直接去掉。
内容的提问来源于stack exchange,提问作者Elberte
相关产品推荐
相关产品推荐

