简体   繁体   中英

How to mock response from private repository in Flutter Bloc Event test?

I want to test the Event to check each condition and I need to mock the repository variable from the abstract class

This is the abstract class for AuthorizationEvent:

@immutable
abstract class AuthorizationEvent {
  final repository = AuthorizationRepository();

  Stream<AuthorizationState> applyAsync({AuthorizationState currentState, AuthorizationBloc bloc});
}

This is the Event:

class LoadAuthorizationEvent extends AuthorizationEvent {
  @override
  Stream<AuthorizationState> applyAsync({AuthorizationState currentState, AuthorizationBloc bloc}) async* {
    try {
      repository.user?.reload();
      if (repository.user != null && !repository.user.isAnonymous) {
        if (AppConfig.useEmailVerification) {
          if (repository.user.emailVerified) {
            yield InAuthorizationState(repository.user);
          } else {
            yield EmailVerificationAuthState(repository.user.email);
          }
        } else {
          yield InAuthorizationState(repository.user);
        }
      } else {
        yield const OutAuthorizationState();
      }
    } catch (_, stackTrace) {
      yield AuthorizationError.handle(_, currentState, stackTrace: stackTrace);
    }
  }
}

This is an old question from the days I didn't know too much about flutter unit testing. The answer to that you need to pass the repository as a parameter and there's an interesting approach for this:

abstract class AuthorizationEvent {
  final AuthorizationRepository _repository;

  AuthorizationEvent(AuthorizationRepository? repository)
      : _repository = repository ?? AuthorizationRepository();

  Stream<AuthorizationState> applyAsync({AuthorizationState currentState, AuthorizationBloc bloc});
}

As you may see you could leave this parameter in null and and instance will be created anyways so your code will still remains the same. Now for unit tests you should mock the repository and pass it through.

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