简体   繁体   English

如何在 Flutter Bloc 事件测试中模拟来自私有存储库的响应?

[英]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我想测试事件以检查每个条件,我需要从抽象 class 模拟repository变量

This is the abstract class for AuthorizationEvent:这是 AuthorizationEvent 的抽象 class:

@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.这是我对 flutter 单元测试不太了解的时候的一个老问题。 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.如您所见,您可以将此参数保留在 null 中,并且无论如何都会创建实例,因此您的代码将保持不变。 Now for unit tests you should mock the repository and pass it through.现在对于单元测试,您应该模拟存储库并通过它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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