【问题标题】:Flutter: Unit Testing a Cubit issuesFlutter:单元测试一个 Cubit 问题
【发布时间】:2021-10-10 12:20:59
【问题描述】:

我一直在尝试为我的 cubit 设置单元测试,但 bloc 测试似乎有问题。只是尝试检查值的初始状态在常规测试中工作得很好,但是一旦我尝试使用 bloc 测试相同的事情,它就会吐出失败,实际是 [0] 处的空列表,我不确定我做错了什么。互联网上的任何内容都无法解决此错误。

//passes
test('initial state of SettingsCubit', () {
  expect(
      settingsCubit.state,
      SettingsState(
          notificationsEnabled: false,
          gpsEnabled: false,
          celsiusEnabled: false,
          expandNavigation: false,
          breakingNewsNotifications: false,
          trendingNotifications: false,
          liveRemindersNotifications: false,
          sportsNotifications: false));
});

//fails
blocTest(
  'initial state of SettingsCubit',
  build: () => SettingsCubit(),
  expect: () => [
    SettingsState(
      expandNavigation: false,
      gpsEnabled: false,
      celsiusEnabled: false,
      notificationsEnabled: false,
      breakingNewsNotifications: false,
      trendingNotifications: false,
      liveRemindersNotifications: false,
      sportsNotifications: false,
    )
  ],
);

错误:

package:bloc_test/src/bloc_test.dart 193:9   testBloc.<fn>
===== asynchronous gap ===========================
dart:async                                   _asyncThenWrapperHelper
package:bloc_test/src/bloc_test.dart         testBloc.<fn>
dart:async                                   runZonedGuarded
package:bloc_test/src/bloc_test.dart 172:9   testBloc
package:bloc_test/src/bloc_test.dart 140:11  blocTest.<fn>
package:bloc_test/src/bloc_test.dart 139:26  blocTest.<fn>
Expected: [
            SettingsState:SettingsState(expandNavigation: false, gpsEnabled: false, celsiusEnabled: false, notificationsEnabled: false,breakingNewsNotifications: false, trendingNotifications: false, liveRemindersNotifications: false, sportsNotifications: false)
          ]
  Actual: []
   Which: at location [0] is [] which shorter than expected

SettingsCubit 和 SettingsState 代码位于: Flutter BLoC Test failures

【问题讨论】:

    标签: flutter unit-testing bloc bloc-test flutter-cubit


    【解决方案1】:

    如果你想测试你的 Cubit 的初始状态,你应该使用第一种方法(适合你的方法)。

    bloc_test 文档中描述了相同测试的第二个版本(blocTest one)不起作用的原因:

    [expect] 是一个可选的Function,它返回一个Matcher bloc 在 [act] 执行后预计会发出。

    意思是,您应该将所有状态更改放在expect 方法中。但是现在,您只是创建了一个 BLoC,之后没有执行任何操作,您的状态不会改变,因此实际结果 - 预期状态更改的列表 - 是空的。

    【讨论】:

    • 我实际上已经完成了所有工作。在我的肘关节上使用 HydratedBloc mixin 似乎是个问题。即使我使用 act 调用状态更改,它仍然会给我错误。如果没有状态变化,我现在了解空列表。谢谢你的回答!
    猜你喜欢
    • 2021-07-28
    • 2022-10-13
    • 1970-01-01
    • 2012-12-01
    • 2022-10-18
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多