0

我正在尝试学习使用 bloc 进行测试。遵循文档中所述的程序。

我有 lib/cubit/counter_cubit.dart 和 lib/cubit/counterState.dart 文件

counter_cubit.dart 是:

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

part 'counter_state.dart';

class CounterCubit extends Cubit<CounterState> {
  CounterCubit() : super(CounterState(counterValue: 0, wasIncremented: false));

  void increment() => emit(
      CounterState(counterValue: state.counterValue + 1, wasIncremented: true));

  void decrement() => emit(CounterState(
      counterValue: state.counterValue - 1, wasIncremented: false));
}

counter_state.dart 是:

part of 'counter_cubit.dart';

class CounterState extends Equatable {
  int counterValue;
  bool wasIncremented;

  CounterState({
    required this.counterValue,
    required this.wasIncremented,
  });

  @override
  List<Object?> get props => [counterValue, wasIncremented];
}

而 counter_cubit_test.dart 是:

import 'package:bloc_basics/cubit/counter_cubit.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  group("CounterCubit", () {
    final CounterCubit counterCubit = CounterCubit();

    test(
        "the initial state for the CounterCubitis CounterState(counterValue:0, wasIncremented:false)",
        () {
      expect(counterCubit.state,
          CounterState(counterValue: 0, wasIncremented: false));
    });

    blocTest(
        "The cubit should emit a CounterState(countervalue:1, wasIncremented:true) when cubit.increment() is called.",
        build: () => counterCubit,
        act: (cubit) => cubit!.increment(),
        expect: () => CounterState(counterValue: 1, wasIncremented: true));
  });
}

该行act: (cubit) => cubit!.increment()正在counter_cubit_test.dart抛出The method 'increment' isn't defined for the type 'Object'.错误。

想不通。

4

1 回答 1

1

method 'X' isn't defined for the type 'Object'.特定对象的类型不清楚时,通常会抛出错误,因此它会退回到一般类型Object

根据您提供的文档,您应该定义 Cubit 类类型及其内部blocTest方法的状态类型:

blocTest<CounterCubit, CounterState>( // <-- Notice the defined types
  "The cubit should emit a CounterState(countervalue:1, wasIncremented:true) when cubit.increment() is called.",
  build: () => CounterCubit(), // <-- Create an instance of a Cubit
  act: (cubit) => cubit.increment(), // <-- ! is not needed here since the type is defined
  expect: () => [ // <-- "expect" should be defined as an array of expected states
    CounterState(counterValue: 1, wasIncremented: true),
  ]
);

于 2022-02-21T22:31:52.983 回答