Hi everyone
I'm currently writting some unit test in my project, and I have some blocs which communicate with other blocs. I injected the bloc inside other bloc and create a streamSubscription to listen changes.
There is a way to test the listen method when changes occur in the bloc?
For instance if i have the following snippet in my bloc constructor:
connectivityBlocSubscription = connectivityBloc.state.listen((state) {
if(state is CurrentConnectivityStatusState){
print(state.connectivityResult);
_connectivityResult = state.connectivityResult;
}
});
Is there a way to mock _connectivityResult field?
Thank you in advance
Hi @jkyon 馃憢
Thanks for opening an issue and great question 馃挴
Regarding your question, you can use mockito to mock the ConnectivityBloc like:
import 'package:mockito/mockito.dart';
// and other imports...
class MockConnectivityBloc extends Mock implements ConnectivityBloc {}
Then you can mock the currentState of the ConnectivityBloc like:
void main() {
MockConnectivityBloc connectivityBloc;
setUp(() {
connectivityBloc = MockConnectivityBloc();
});
group('MyGroup', () {
test('MyTest', () {
// you can now control the connectivityBloc state and make it whatever you'd like.
when(connectivityBloc.currentState).thenReturn(CurrentConnectivityStatusState(...));
});
});
}
Closing for now but hope that helps and let me know if you have any questions! 馃憤
thank you @felangel
It works perfectly!
Hi @felangel
I have same issue, but I don't understand your solution.
say there are two bloc, A_Bloc and B_Bloc, B_Bloc is depend on A_Bloc
`
class B_Bloc extends Bloc<B_Event, B_State> {
final A_Bloc a_bloc;
StreamSubscription a_BlocSubscription;
B_Bloc({@required this.a_bloc}) : assert(a_bloc != null) {
a_BlocSubscription = a_bloc.listen((state) {
if (state is Some_A_State) {
this.add(Some_B_Event());
}
});
}
}
`
now I want to test this bloc logic,
`
blocTest(
'should fire event in response to a_bloc state change',
build: () {
when(a_Bloc.state)
.thenReturn(Some_A_State());
return b_Bloc;
},
act: (B_Bloc bloc) async {
a_Bloc..add(Some_A_Event()); // fire A_Event, trigger A_State change,
// bloc.a_bloc.add(Some_A_Event()); // this won't work neither
},
expect: <B_State>[
Some_B_State(),
],
);
`
the idea is: add A_Event triggers A_State change, B_Bloc should notice A_State changed, then add B_Event, however when I run test, the actual output is a list of empty state.
I don't know how to test this bloc.listen logic, any suggestion?
Most helpful comment
thank you @felangel
It works perfectly!