Describe the bug
I can't use blocTestmethods for testing exceptions using cubit with Future methods.
To Reproduce
Steps to reproduce the behavior:
'index 3 or more should throw exception, unit test working incorrectly'Expected behavior
The test passes, because expected error have been thrown.
Additional context
I have checked why blocTestdoesn't work with Future methods. It is because it expects CubitUnhandledErrorException, otherwise unit test will throw error, making the test fail.
I have created second unit test to show that it is indeed the reason - I simply throw exception wrapped in CubitUnhandledErrorExceptionand it works correctly in case of using Future.error.
See: https://github.com/JanuszHain/bloc_test_cubit_exception/blob/master/lib/test_cubit.dart
I have some questions regarding testing.
Future.error? I have tried to debug it, but haven't noticed anything that could lead to unit test not being able to end.CubitUnhandledErrorExceptionis needed in blocTest? Legacy cubit library didn't have such thing and I think it could be possible to use blocTestwithout wrapping exceptions. (https://github.com/felangel/cubit/blob/master/packages/cubit_test/lib/src/cubit_test.dart)Update: In our team we have decided to catch expected errors and make states for it (we have to handle them), if we don't know about exceptions, it should crash (as it is development failure). So we don't have to test exceptions from cubit at all, instead we have to test if correct error state was emitted. I am not closing the issue, because the problem above persists.
Hi @JanuszHain 馃憢
Thanks for opening an issue!
final exception = Exception('oops');
blocTest<ExceptionCubit, int>(
'captures uncaught exceptions',
build: () => ExceptionCubit(),
act: (cubit) => cubit.throwException(exception),
errors: <Matcher>[equals(exception)],
);
blocTest<ExceptionCubit, int>(
'captures calls to addError',
build: () => ExceptionCubit(),
act: (cubit) => cubit.addError(exception),
errors: <Matcher>[equals(exception)],
);
where ExceptionCubit is:
import 'package:bloc/bloc.dart';
class ExceptionCubit extends Cubit<int> {
ExceptionCubit() : super(0);
void throwException(Exception e) => throw e;
}
Let me know if that helps and thanks again for reporting this 馃憤
Hello,
Thank you, I have checked the changes and works nicely :)
And thank you for explanation of exception testing.
Greetings,
Janusz
Hi @felangel ,
I have checked different unit test and it doesn't end test too if the error is thrown in expect, you can see this on branch that I created to show the bug (splash_cubit_test):
https://github.com/JanuszHain/bloc_test_cubit_exception/tree/exception_in_expect_not_ending_test
It looks like try catch inside blocTest should cover more code, because exception thrown in actworks ok after library update, and in expect not. I am not sure about other functions, but it seems like build and verify can throw exceptions too, which will not end the test with failure.