svprdga
svprdga

Reputation: 2549

Flutter: Provider error when mocking stream within a Mock

I have a bloc object which contains a stream:

Bloc {
  final _controller = StreamController<MainEvents>.broadcast();

  Stream<MainEvents> get stream => _controller.stream;
}

I'm trying to mock this object in order to do another test using Mockito:

Bloc bloc = Bloc();

final _controller = StreamController<MainEvents>.broadcast();
when(mainBloc.stream).thenAnswer((_) => _controller.stream);

Then I construct a test widget providing this bloc via provider package:

testWidget = MultiProvider(
  providers: [
    Provider<Bloc>.value(value: bloc)
  ],
  child: Something(),
);

But when I execute the test, this provider constructions fails with the error:

The following assertion was thrown building Provider(dirty, state: _DelegateWidgetState#9ee17): Tried to use Provider with a subtype of Listenable/Stream (Bloc).

This is likely a mistake, as Provider will not automatically update dependents when Bloc is updated. Instead, consider changing Provider for more specific implementation that handles the update mecanism, such as:

  • ListenableProvider
  • ChangeNotifierProvider
  • ValueListenableProvider
  • StreamProvider

The app works ok but the test fails, any help?

Upvotes: 3

Views: 1805

Answers (1)

Omatt
Omatt

Reputation: 10511

The issue here was caused by the Provider you're trying to use on MultiProvider.providers. As mentioned in the logs, you may need to consider changing Provider to a more specific implementation.

Consider modifying the provider to ListenableProvider and see if it fits your use case.

MultiProvider(
  providers: [
    ListenableProvider<Bloc>.value(value: bloc)
  ],
  ...
)

Upvotes: 0

Related Questions