【发布时间】:2021-09-28 12:03:16
【问题描述】:
我目前正在尝试为项目构建小部件测试(专注于 TDD)。我正在使用 Injectable 来生成依赖注入以及在各种实现之间交换的环境。我遇到的问题是我无法像在单元测试中那样使用@GenerateMocks([IAuthRepository]),因此需要将模拟注入 GetIt。
@Environment("test")
@LazySingleton(as: IAuthRepository)
class MockFirebaseAuthFascade with Mock implements IAuthRepository {}
在我的小部件测试中,我首先注入文本环境,然后使用getIt<IAuthRepository>() 调用模拟实例,以便我可以在测试中使用when 和verify:
void main() {
setUpAll(() async {
configureInjection(Environment.test);
});
testWidgets(
'GIVEN form is initial state '
'WHEN ElevatedButton is pressed '
'THEN see two error messaged below TextField', (tester) async {
// Arrange
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: const [
Localize.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: Localize.delegate.supportedLocales,
home: BlocProvider(
create: (context) => getIt<SignInFormBloc>(),
child: const Scaffold(
body: SignInForm(),
),
),
),
);
final mockAuth = getIt<IAuthRepository>();
final Finder signIn =
find.byKey(const Key("auth_sign_in_with_email_button"));
// Act
await tester.pumpAndSettle();
await tester.tap(signIn);
await tester.pump(const Duration(seconds: 1));
// Assert
verifyNever(mockAuth.resetPassword(email: anyNamed("named")));
});
}
我得到的是 anyNamed("named") 上的一个错误,因为它只是被模拟了,而不是像在我的单元测试中那样使用 @GenerateMocks([IAuthRepository])。我不明白,或者找不到答案,我应该如何将@GenerateMocks 与 Injectable 一起使用?还是有另一种方法可以为我的测试环境生成更好的模拟?
非常感谢任何指导或建议。
【问题讨论】:
标签: flutter unit-testing dart mockito injectable