我正在嘲笑我使用 firebase 的注册功能。我的问题是,当我在 BlocTest 中调用构建器时,不知何故它的值变为 null。我不明白,因为 kMockTeacher 在我的 user_model.dart 中被定义为 UserModel:
final kMockTeacher = UserModel(
firstName: 'Logan',
lastName: 'V',
email: '[email protected]',
role: UserRole.teacher,
token: '',
id: '1');
构建:auth_test.dart中的()
when(
authService.signUpWithEmailAndPassword(registrationModel),
).thenReturn(
Future<UserModel>.value(kMockTeacher),
);
services.dart
Future<UserModel> signUpWithEmailAndPassword(
final UserRegistrationModel user,
);
auth_test.dart:
import 'package:bloc_test/bloc_test.dart';
import 'package:edtech/backend/services/services.dart';
import 'package:edtech/blocs/auth_cubit/auth_bloc.dart';
import 'package:edtech/models/models.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class MockedDatabaseService extends Mock implements DatabaseService {}
class MockedAuthService extends Mock implements AuthService {}
void main() {
group("Test Sign Up functions", () {
late AuthService authService;
late DatabaseService databaseService;
late AuthBloc bloc;
late UserRegistrationModel registrationModel;
setUpAll(() {
authService = MockedAuthService();
databaseService = MockedDatabaseService();
registrationModel = UserRegistrationModel(
password: 'password',
firstName: kMockTeacher.firstName,
lastName: kMockTeacher.lastName,
email: kMockTeacher.email,
role: kMockTeacher.role);
bloc = AuthBloc(UnAuthenticatedState(), authService);
});
blocTest<AuthBloc, AuthState>(
'emits AuthLoading followed by AuthenticatedState',
build: () {
when(
authService.signUpWithEmailAndPassword(registrationModel),
).thenReturn(
Future<UserModel>.value(kMockTeacher),
);
return bloc;
},
act: (bloc) => bloc.signUp(user: registrationModel),
expect: () => [
AuthLoadingState(),
AuthenticatedState(user: kMockTeacher),
],
);
tearDown(() {
bloc.close();
});
});
}
我在调试模式下运行了测试,试图获取
Future<UserModel>.value(kMockTeacher),
的值,但在获取它之前编译失败了。
使用 thenReturn 返回 Future 或 Stream 将抛出
。ArgumentError
由于您的
authService.signUpWithEmailAndPassword(registrationModel)
返回 Future,因此您必须使用 thenAnswer。
when(
authService.signUpWithEmailAndPassword(registrationModel),
).thenAnswer((_) => Future<UserModel>.value(kMockTeacher));
请参阅有关异步存根的快速说明以获取更多信息。