I am trying to test a class with a function like that
class A {
void doStuff() {
// Do stuff...
notifyListeners();
}
}
I am currently using the flutter-test
package to automate my tests.
My test looks like this:
void main() {
final myInstance = A();
group("Class A", () {
test("should correctly do stuff", () async {
myInstance.doStuff();
expect(...);
});
});
}
The test is working and expect
yields the correct result.
However, console shows an error message:
The following StateError was thrown while dispatching notifications for Class A:
Bad state: Future already completed
What causes this error and how can I prevent it from happening?
Turns out, notifyListeners()
was the root-cause here.
It threw an error, presumably because it was not yet initialized.
By waiting for its initialization, the error has stopped occuring.
See TestWidgetsFlutterBinding.ensureInitialized
for reference
setUpAll(() {
TestWidgetsFlutterBinding.ensureInitialized();
});