我有一个 bloc,它侦听身份验证事件的流(侦听 firebase 用户事件)。我的块是;
class AuthenticationBloc
extends Bloc<AuthenticationEvent, AuthenticationLoadingState> {
StreamSubscription<AuthenticationDetail> streamSubscription;
CheckAuthenticationStatus authenticationStatus;
AuthenticationBloc({@required CheckAuthenticationStatus authenticationStatus})
: assert(authenticationStatus != null),
assert(authenticationStatus.getStream() != null),
this.authenticationStatus = authenticationStatus,
super(AuthenticationLoadingState().init()) {
this.streamSubscription = this
.authenticationStatus
.getStream()
.listen((AuthenticationDetail detail) async* {
print(detail.toString());
add(StatusChanged(detail));
});
}
@override
Stream<AuthenticationLoadingState> mapEventToState(
AuthenticationEvent event) async* {
if (event is ListenToAuthenticationEvents) {
print('well well well');
} else if (event is StatusChanged) {
print('yeeee');
}
}
@override
Future<void> close() {
this.streamSubscription?.cancel();
return super.close();
}
Future<AuthenticationLoadingState> init() async {
return state.clone();
}
}
提供用例是;
class CheckAuthenticationStatus
implements UseCaseListner<AuthenticationDetail> {
final AuthenticationRepository authenticationRepository;
CheckAuthenticationStatus({@required this.authenticationRepository});
@override
Stream<AuthenticationDetail> getStream() =>
authenticationRepository.getAuthDetailStream();
}
我正在尝试编写一个块测试,我可以在其中模拟用例并添加我自己的流,我可以按如下方式向其发送事件;
class MockCheckAuthenticationStatus extends Mock
implements CheckAuthenticationStatus {}
void main() {
MockCheckAuthenticationStatus authenticationStatus;
AuthenticationBloc authenticationBloc;
StreamController controller;
Stream<AuthenticationDetail> stream;
setUp(() {
controller = StreamController<AuthenticationDetail>();
stream = controller.stream;
authenticationStatus = MockCheckAuthenticationStatus();
});
test('initial state is correct', () async {
var authenticationDetail = AuthenticationDetail(isValid: true);
when(authenticationStatus.getStream()).thenAnswer((_) => stream);
authenticationBloc =
AuthenticationBloc(authenticationStatus: authenticationStatus);
//this should action, but doesnt, why?
controller.add(authenticationDetail);
await untilCalled(authenticationStatus.getStream());
verify(authenticationStatus.getStream());
});
tearDown(() {
authenticationBloc?.close();
controller?.close();
});
}
期望 controller.add(authenticationDetail)
将生成事件,我希望去
mapEventToState
在集团中的那些事件上。然而,这并没有发生。
简而言之,我如何通过发送流事件而不是编程方式使用 bloc.add() 事件来测试 bloc。
答案 0 :(得分:0)
问题的前提是基于 Firebase auth 官方文档所述
Events are fired when the following occurs:
- Right after the listener has been registered.
- When a user is signed in.
- When the current user is signed out.
所以不是注册一个 listener ,而是通过一个事件调用 getUser 。仅注册侦听器也应该触发第一个事件,然后我们可以使用该事件进行相应的导航。我的测试目的是模拟第一个事件。
代码中的错误是 AuthenticationBloc 构造函数中 async*
行上的 .listen((AuthenticationDetail detail) async* {