如何处理“断言错误不是类型转换中'Exception'类型的子类型

How to deal with "Assertion error is not a subtype of of type 'Exception' in type cast

当我的测试失败时,我在尝试在我的项目中实施 blocTesting 时遇到了一个奇怪的错误。它如下:

Expected: [
            SignUpCreateAccountLoading:SignUpCreateAccountLoading(),
            SignupInitial:SignupInitial()
          ]
  Actual: [
            SignUpCreateAccountLoading:SignUpCreateAccountLoading(),
            SignUpCreateAccountFailure:SignUpCreateAccountFailure(type '_AssertionError' is not a subtype of type 'Exception' in type cast, nikunj@gmail.com),
            SignupInitial:SignupInitial()
          ]

我需要在这个项目的集团测试中使用真实的 api。

下面是 blocTest、bloc、blocEvent、blocState 和存储库文件。

SignupBlocTest

import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mynovatium/features/login/bloc/authentication/authentication_bloc.dart';
import 'package:mynovatium/features/login/repositories/authentication_repository.dart';
import 'package:mynovatium/features/signup/bloc/signup_bloc.dart';

void main() async {
  group('SignupBloc', () {
    late SignUpBloc signUpBloc;
    setUp(() {
      signUpBloc = SignUpBloc();
    });

    test('initial state of the bloc is [AuthenticationInitial]', () {
      expect(SignUpBloc().state, SignupInitial());
    });

    group('SignUpCreateAccount', () {
      blocTest<SignUpBloc, SignUpState>(
        'emits [SignUpCreateAccountLoading, SignupInitial] '
        'state when successfully Signed up',
        setUp: () {},
        build: () => SignUpBloc(),
        act: (SignUpBloc bloc) => bloc.add(const SignUpCreateAccount(
            'Nevil', 'abcd', 'nikunj@gmail.com', 'english',),),
        wait: const Duration(milliseconds: 10000),
        expect: () => [
          SignUpCreateAccountLoading(),
          SignupInitial(),
        ],
      );
    });
  });
}

signupBloc

import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:core/models/exception/kbm_exception.dart';
import 'package:equatable/equatable.dart';
import 'package:mynovatium/features/signup/repositories/signup_repository.dart';

part 'signup_event.dart';
part 'signup_state.dart';

class SignUpBloc extends Bloc<SignUpEvent, SignUpState> {
  final SignUpRepository _signUpRepository = SignUpRepository();

  SignUpBloc() : super(SignupInitial()) {
    // Register events here
    on<SignUpCreateAccount>(_onSignUpCreateAccount);
  }

  Future<void> _onSignUpCreateAccount(SignUpCreateAccount event, Emitter<SignUpState> emit) async {
    emit(SignUpCreateAccountLoading());
    try {
      final bool _success = await _signUpRepository.createAccount(event.firstName, event.lastName, event.eMailAddress, event.language);

      if (_success) emit(SignUpCreateAccountSuccess());
    } catch (e) {
      emit(SignUpCreateAccountFailure(exception: e.toString(), email: event.eMailAddress));
      emit(SignupInitial());
    }
  }
}

Signup_event

part of 'signup_bloc.dart';

abstract class SignUpEvent extends Equatable {
  const SignUpEvent();

  @override
  List<Object> get props => <Object>[];
}

class SignUpCreateAccount extends SignUpEvent {
  final String firstName;
  final String lastName;
  final String eMailAddress;
  final String language;

  const SignUpCreateAccount(this.firstName, this.lastName, this.eMailAddress, this.language);
  @override
  List<Object> get props => <Object>[firstName, lastName, eMailAddress, language];
}

Signup_state

part of 'signup_bloc.dart';

abstract class SignUpState extends Equatable {
  const SignUpState();

  @override
  List<Object> get props => <Object>[];
}

class SignupInitial extends SignUpState {}

class SignUpCreateAccountLoading extends SignUpState {}

class SignUpCreateAccountSuccess extends SignUpState {}

class SignUpCreateAccountFailure extends SignUpState {
  final String exception;
  final String email;

  const SignUpCreateAccountFailure({required this.exception, required this.email});
  @override
  List<Object> get props => <Object>[exception, email];
}

注册资料库

import 'dart:convert';

import 'package:core/models/exception/kbm_exception.dart';
import 'package:http/http.dart';
import 'package:mynovatium/app/constants/endpoints.dart';
import 'package:mynovatium/app/helper/api_request.dart';
import 'package:mynovatium/app/model/global_customer_model.dart';

class SignUpRepository {
  Future<bool> createAccount(String _firstName, String _lastName, String _eMailAddress, String _language) async {
    final Response _response;
    try {
      _response = await CEApiRequest().post(
        Endpoints.createCustomerAPI,
        jsonData: <String, dynamic>{
          'firstName': _firstName,
          'lastName': _lastName,
          'email': _eMailAddress,
          'language': _language,
          'responseUrl': Endpoints.flutterAddress,
        },
      );

      final Map<String, dynamic> _customerMap = jsonDecode(_response.body);
      final CustomerModel _clients = CustomerModel.fromJson(_customerMap['data']);

      if (_clients.id != null) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      final KBMException _exception = e as KBMException;
      throw _exception;
    }
  }
}

一个 _AssertionError 被扔到某处,但您正试图将其转换为 catch 中的异常。相反,您应该重新抛出您期望的异常并以不同的方式处理其他类型。下面我return false,但是你可以选择合适的行为来满足你的需要。

try {
  ...
} on KBMException catch (e) {
  rethrow;
} catch (e) {
  // Not a KBMException so returning false.
  return false;
}