Flutter [bloc_test] not throwing a expection

201 views Asked by At

When I want to test my completedIntroTutorial method, I'd like to also test the on Exception catch for that I call inside the unit test thenThrow, but it isn't throwing an exception. I have tried to use the following things in the thenThrow method: Exception, Exception(), const IntroCubitError(appError: tAppError)but neither of these things will go into the Exception function in the Cubit. When I debug the test and attaching breakpoints in the IntroCubit, it is only going into the if statement but never in the exception.

I have the following Packages installed with their Version:

dependencies
  flutter_bloc: ^8.1.1
  equatable: ^2.0.5
  bloc: ^8.1.0

dev_dependencies
  bloc_test: ^9.1.0
  mocktail: ^0.3.0
  build_runner: ^2.3.3

Intro Cubit

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../config/error/error.dart';

part 'intro_cubit_state.dart';

class IntroCubit extends Cubit<IntroState> {
  final SharedPreferences sharedPreferences;

  IntroCubit({
    required this.sharedPreferences,
  }) : super(IntroCubitInitial());

  @visibleForTesting
  static const String completedIntro = 'completedIntro';

  void completedIntroTutorial() {
    emit(IntroCubitInitial());
    emit(IntroCubitLoading());
    try {
      final bool = sharedPreferences.getBool(completedIntro) ?? false;
      if (bool) {
        emit(
          IntroCubitSuccess(boolean: bool),
        );
      } else {
        emit(
          IntroCubitSuccess(boolean: bool),
        );
      }
    } on Exception catch (exception) {
      emit(
        IntroCubitError(
          appError: AppError(
            message: exception.toString(),
          ),
        ),
      );
    }
  }
}

unit test

import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:app/config/error/error.dart';
import 'package:app/presentation/intro/cubit/intro_cubit_cubit.dart';

class MockIntroCubit extends Mock implements IntroCubit {}

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  late SharedPreferences sharedPreferences;
  late IntroCubit introCubit;
  late MockIntroCubit mockIntroCubit;

  setUp(() async {
    SharedPreferences.setMockInitialValues({});
    sharedPreferences = await SharedPreferences.getInstance();
    introCubit = IntroCubit(sharedPreferences: sharedPreferences);
    mockIntroCubit = MockIntroCubit();
  });

  group('Intro Cubit Test', () {
    const AppError tAppError = AppError(message: 'Failed to save bool');

    blocTest<IntroCubit, IntroState>(
      'emits [IntroCubitInitial, IntroCubitLoading, IntroCubitError] when [completedIntroTutorial] is failed.',
      setUp: () => when(() => mockIntroCubit.completedIntroTutorial())
          .thenThrow(tAppError),
      build: () => introCubit,
      act: (cubit) => cubit.completedIntroTutorial(),
      expect: () => <IntroState>[
        IntroCubitInitial(),
        IntroCubitLoading(),
        const IntroCubitError(appError: tAppError),
      ],
    );
  });
}

1

There are 1 answers

0
Padmaja Rani On

try below example

on top of main function

class MockRepository extends Mock implements Repository {}
blocTest<MyBloc, State>(
        'emits Loading and SocketExceptionState - on getData failure',
        build: () {
         final mockRepository = MockRepository();
          when(() => mockUserRepository
              .getData('params if any'),)
              .thenThrow(SocketExceptionState);
          return MyBloc(mockRepository);
        },
        act: (bloc) => bloc
            .getData('params if any'),
        errors: () => [SocketExceptionState]);