![](/img/trans.png)
[英]FLUTTER: When testing cubit, loading state isn't emitted, only loaded state is
[英]Unit Testing a Cubit
这是我第一次尝试测试我的Cubit
class,所以请多多包涵,因为我在尝试了好几个小时后完全没有想法。
我正在尝试测试一个看起来像这样的简单肘尺:
@injectable
class ResetPasswordCubit extends Cubit<ResetPasswordState> {
ResetPasswordCubit() : super(ResetPasswordInitial());
void attemptPasswordReset({required ResetPasswordParams params}) async {
emit(ResetPasswordLoading());
emit(ResetPasswordLoaded());
}
}
我想要做的就是验证这两种状态是否按顺序发出。 根据文档,有几种方法可以做到这一点,但我什至不确定我应该使用哪一种。 我更愿意使用单元测试,尽管我都试过了。 这是我所拥有的:
class MockResetPasswordCubit extends MockCubit<ResetPasswordState>
implements ResetPasswordCubit {}
@GenerateMocks([ResetPassword])
void main() {
late MockResetPassword mockResetPassword;
late MockResetPasswordCubit cubit;
late ResetPasswordParams params;
setUp(() {
mockResetPassword = MockResetPassword();
cubit = MockResetPasswordCubit();
params = const ResetPasswordParams(
pin: "1234", password: "hello", confirmPassword: "hello");
when(mockResetPassword.call(params))
.thenAnswer((_) async => const Right(ResetPasswordResult.validated));
});
blocTest<ResetPasswordCubit, ResetPasswordState>(
'when attempt to validate password is made then loading state is emitted',
build: () => cubit,
act: (cubit) => cubit.attemptPasswordReset(params: params),
expect: () => [ResetPasswordLoading(), ResetPasswordLoaded()]);
}
这是显示的错误:
预期:[“ResetPasswordLoading”实例,“ResetPasswordLoaded”实例]
实际的: []
其中:位置 [0] 是 [],比预期的要短
我真的没有想法,所以希望有人可以让我直截了当。 谢谢。
似乎您正在尝试测试ResetPasswordCubit
但您所做的是模拟它,因此无法测试实际的 cubit 行为。
只是不要模拟你想要测试的手肘并创建它的一个实例:
blocTest<ResetPasswordCubit, ResetPasswordState>(
'when attempt to validate password is made then loading state is emitted',
build: () => ResetPasswordCubit(), // <-- Creating an instance of Cubit
act: (cubit) => cubit.attemptPasswordReset(params: params),
expect: () => [ResetPasswordLoading(), ResetPasswordLoaded()],
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.