'"Bad state: Cannot call `when` within a stub response", "type 'Null' is not a subtype of type [...]"
I wrote a few unit and widget tests for my Flutter app. They all pass when called from the testing window out of VSCode:
But when I call flutter test
from the terminal or run the tests in Android Studio they do not pass and always throw the same 2 errors, as seen here:
What does VSCode do differently, that they all pass on there but fail from terminal?
Solution 1:[1]
If you use dart/flutter with null safety and therefore mockito with null safety, you have to closely follow this: https://github.com/dart-lang/mockito/blob/master/NULL_SAFETY_README.md
I had a simple error in my imports and didn't use the auto-generated MockRepository but instead some old file that wasn't null safe! If you encounter the mistakes in the title of the question, I am 100% confident you did not implement mockito for null safety correctly.
Why the tests passed on VSCode is still a mysterium but doesn't matter for me, since they pass now everywhere.
Solution 2:[2]
With sound null safety the invocation when
should not happen from the test code or from setUp
. It should be made directly from the test's main
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nimantha |
Solution 2 | polina-c |