Search⌘ K
AI Features

Solution: Testing ShoppingCartCubit

Explore how to effectively test ShoppingCartCubit by mocking the cubit, using whenListen() to simulate state streams, and writing unit tests for adding, removing, and clearing cart items. This lesson helps you verify correct state emissions and ensures your shopping cart behaves as expected within the BLoC pattern.

We hope that the exercise was simple! It’s time to see a possible solution to the exercise.

Mocking ShoppingCartCubit

Mocking the ShoppingCartCubit is done by extending the MockCubit class provided to us by the bloc_test library.

Dart
class MockShoppingCartCubit extends MockCubit<ShoppingCartState>
implements ShoppingCartCubit {}

Implementing whenListen()

Dart
ShoppingCartCubit shoppingCartCubit = MockShoppingCartCubit();
whenListen(
shoppingCartCubit,
Stream.fromIterable([
ShoppingCartUpdated(shoppingCart),
ShoppingCartUpdated(shoppingCart2)
]),
initialState: ShoppingCartInitial());
  • Line 1: This creates a MockShoppingCartCubit instance called shoppingCartCubit.

  • Line 3: This provides the first parameter of the whenListen() ...