gpt4 book ai didi

flutter - bloc_test : Bad state: Cannot emit new states after calling close

转载 作者:行者123 更新时间:2023-12-05 05:36:08 24 4
gpt4 key购买 nike

我在 Flutter 的测试部分遇到了问题,我为使用 cubit 的简单计数器应用程序编写了一个测试,但是当我运行所有测试时它给了我 header 中提到的错误,有人知道为什么吗?

有必要说,当我一个一个地运行测试时,所有测试都成功运行,但是当我运行所有组时,它会在第二个和第三个测试中返回该错误...

这些是我的代码:

group("Counter Cubit", () {
CounterCubit counterCubit = CounterCubit();
setUp(() {
//counterCubit = CounterCubit();
});

tearDown(() {
counterCubit.close();
});

test("The initial state for counterCubit is CounterState(counterValue: 0)",
() {
expect(counterCubit.state, CounterState(0, false));
});

blocTest(
"The cubit should emit CounterState(counter: 1, isIncrement: true) while we call
counterCubit.increment() ",
build: () => counterCubit,
act: (CounterCubit cubit) => cubit.increment(),
expect: () => [CounterState(1, true)]);

blocTest(
"The cubit should emit CounterState(counter: -1, isIncrement: false) while we call
counterCubit.decrement() ",
build: () => counterCubit,
act: (CounterCubit cubit) => cubit.decrement(),
expect: () => [CounterState(-1, false)]);
});

我的肘和状态如下:

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

void increment() => emit(CounterState(state.counter + 1, true));

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

然后这样说:

class CounterState extends Equatable {
final int counter;
final bool isIncremented;
CounterState(this.counter, this.isIncremented);

@override
List<Object?> get props => [counter, isIncremented];
}

最佳答案

bloc_test文档说:

blocTest creates a new bloc-specific test case with the given description. blocTest will handle asserting that the bloc emits the expected states (in order) after act is executed. blocTest also handles ensuring that no additional states are emitted by closing the bloc stream before evaluating the expectation.

所以基本上当你运行时:

blocTest(
// ...
build: () => counterCubit, // Same instance for all tests
// ...
);

它处理您的 BLoC 实例(您通过 build 参数传递)。因此,由于第二个测试使用与第一个测试相同的实例,因此它会抛出异常,因为实际上它已被最后一个 blocTest 调用(在先前的测试中)关闭。

它还回答了为什么一个一个地运行测试有效而不是组。

修复在运行 blocTest 时传递一个新实例(通过相同的参数):

blocTest(
// ...
build: () => CounterCubit(), // Create a new instance
// ...
);

关于flutter - bloc_test : Bad state: Cannot emit new states after calling close,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73345889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com