简体   繁体   中英

Unit Testing a Cubit

This is my first effort at testing my Cubit class, so please bear with me as I am completely out of ideas after trying for many hours.

I'm trying to test a simple cubit that looks like this:

@injectable
class ResetPasswordCubit extends Cubit<ResetPasswordState> {

  ResetPasswordCubit() : super(ResetPasswordInitial());

  void attemptPasswordReset({required ResetPasswordParams params}) async {
    emit(ResetPasswordLoading());
    emit(ResetPasswordLoaded());
  }
}

All I want to do is to verify that both of these states were emitted in order. According to the docs , there are a couple of ways to do this, but I'm not even sure which one I should be using. I would prefer to use the unit test, although I've tried both. Here is what I have:

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()]);
}

And this is the error that gets displayed:

Expected: [Instance of 'ResetPasswordLoading', Instance of 'ResetPasswordLoaded']
Actual: []
Which: at location [0] is [] which shorter than expected

I'm really out of ideas, so hoping someone can set me straight. Thanks.

It seems that you are trying to test the ResetPasswordCubit but what you do is mock it, hence it is not possible to test the actual cubit's behaviour.

Just do not mock the cubit you want to test and create an instance of it:

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()],
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM