在 Flutter Mockito BlocTest 中找不到初始状态

Sar*_*ran 0 unit-testing mockito dart flutter bloc

我正在尝试做一个非常简单的 blocTest 来测试初始状态。但低于错误。有趣的是,我确实有另一个工作组并在同一个项目中进行测试。我逐行检查以查看是否有任何不匹配,但一切看起来都很完美,除了“行为”之外,我正在其他地方而不是这里做,假设与此初始状态测试无关。知道为什么这个集团会发生这种情况吗?

Expected: [ReadyToAuthenticateState:ReadyToAuthenticateState()]
  Actual: []
   Which: at location [0] is [] which shorter than expected
Run Code Online (Sandbox Code Playgroud)

我的集体测试

  late MockUserAuthenticationUseCase mockUsecase;
  late UserAuthenticationBloc authBloc;
  setUp(() {
    mockUsecase = MockUserAuthenticationUseCase();
    authBloc = UserAuthenticationBloc(usecase: mockUsecase);
  });

blocTest<UserAuthenticationBloc, UserAuthenticationState>(
    'emits [MyState] when MyEvent is added.',
    build: () => authBloc,
    expect: () => <UserAuthenticationState>[ReadyToAuthenticateState()],
  );
Run Code Online (Sandbox Code Playgroud)

我的集团

class UserAuthenticationBloc
    extends Bloc<UserAuthenticationEvent, UserAuthenticationState> {
  final UserAuthenticationUseCase usecase;

  UserAuthenticationBloc({required this.usecase})
      : super(ReadyToAuthenticateState()) {
    on<UserAuthenticationEvent>((event, emit) {
      if (event is AuthenticateUserWithCredentialsEvent) {
        _processReadyToAuthenticateEvent(event);
      }
    });
  }

  void _processReadyToAuthenticateEvent(
      AuthenticateUserWithCredentialsEvent event) async {
    await usecase(
        UserAuthenticationUseCaseParams(event.username, event.password));
  }
}
Run Code Online (Sandbox Code Playgroud)

更新#1:我也将初始状态期望插入到其他工作块测试中,并得到了相同的错误。看来我们不应该测试初始状态。

mko*_*lys 6

这是包expect中的属性文档bloc_test

/// [expect] is an optional `Function` that returns a `Matcher` which the `bloc`
/// under test is expected to emit after [act] is executed.
Run Code Online (Sandbox Code Playgroud)

这意味着,在expect回调内部,您应该只放置发出的状态。初始状态是初始状态,在将事件添加到 BLoC 后不会发出它。

如果您想验证 BLoC 的初始状态,您可以为其编写一个单独的测试:

test('should set initial state', () {
  expect(authBloc.state, ReadyToAuthenticateState());
});
Run Code Online (Sandbox Code Playgroud)