我正在使用 AsyncValue 提供程序测试一些 Flutter/Dart 代码。我几乎从字面上使用Andrea的例子。我的监听器扩展了 Mock,但是当我验证它时,测试失败并显示“用于非 mockito 对象”。
这里所说的是哪个非mockito对象?我的听众是一个模仿者。
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:riverpod/riverpod.dart';
// a generic Listener class, used to keep track of when a provider
// notifies its listeners
class Listener<T> extends Mock {
void call(T? previous, T next);
}
void main() {
group('GeoData', () {
// This is a variation of Andrea's AuthController example minus the
// extra mock'ed AuthRepository dependency.
// https://codewithandrea.com/articles/unit-test-async-notifier-riverpod/
test('initialization with default GeoInfo data', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final listener = Listener<AsyncValue<GeoInfo>>();
container.listen(geoDataProvider, listener, fireImmediately: true);
// ---> this is the line that fails the test with "Used on a non-mockito object"
verify(() => listener(null, const AsyncData<GeoInfo>(GeoInfo.empty())));
verifyNoMoreInteractions(listener);
});
});
}
'''
哎呀,我在这上面花了太多时间,在找到它之前,我已经掉进了不止一个兔子洞了。这与错误地初始化模拟无关,而与mocktail和mockito之间的差异有关🤦u200d♀️
这两个包非常相似,但验证调用的语法不同。
无酒精鸡尾酒:
verify(() => listener(null, const AsyncData<GeoInfo>(GeoInfo.empty())));
模拟:
verify(listener.call(null, const AsyncData<GeoInfo>(GeoInfo.empty()))).called(1);
一旦我更改了对 Mockito 语法的调用,测试就按预期通过了。