Flutter BLoC 测试失败

2024-02-06

目前正在尝试对我的肘节实施单元测试,我感觉严重缺乏 BLoC 在线测试文档或有用的示例。谁能解释一下我在设置这个测试时做错了什么。我似乎无法弄清楚问题是什么。如果有人能告诉我我能做些什么来解决这个问题,我将不胜感激。

设置状态文件:

class SettingsState extends Equatable {
  late final bool expandNavigation;
  late final bool gpsEnabled;
  late final bool celsiusEnabled;
  late final bool notificationsEnabled;
  late final bool breakingNewsNotifications;
  late final bool trendingNotifications;
  late final bool liveRemindersNotifications;
  late final bool sportsNotifications;
  SettingsState({
    required this.notificationsEnabled,
    required this.gpsEnabled,
    required this.celsiusEnabled,
    required this.expandNavigation,
    required this.breakingNewsNotifications,
    required this.trendingNotifications,
    required this.liveRemindersNotifications,
    required this.sportsNotifications,
  });
  SettingsState copyWith({
    bool? gpsEnabled,
    bool? celsiusEnabled,
    bool? expandNavigation,
    bool? notificationsEnabled,
    bool? breakingNewsNotifications,
    bool? trendingNotifications,
    bool? liveRemindersNotifications,
    bool? sportsNotifications,
  }) {
    return SettingsState(
      expandNavigation: expandNavigation ?? this.expandNavigation,
      gpsEnabled: gpsEnabled ?? this.gpsEnabled,
      celsiusEnabled: celsiusEnabled ?? this.celsiusEnabled,
      notificationsEnabled: notificationsEnabled ?? this.notificationsEnabled,
      breakingNewsNotifications:
          breakingNewsNotifications ?? this.breakingNewsNotifications,
      trendingNotifications:
          trendingNotifications ?? this.trendingNotifications,
      liveRemindersNotifications:
          liveRemindersNotifications ?? this.liveRemindersNotifications,
      sportsNotifications: sportsNotifications ?? this.sportsNotifications,
    );
  }
  // mapping user settings
  Map<String, dynamic> toMap() {
    return {
      'expandNavigation': expandNavigation,
      'gpsEnabled': gpsEnabled,
      'celsiusEnabled': celsiusEnabled,
      'notificationsEnabled': notificationsEnabled,
      'breakingNewsNotifications': breakingNewsNotifications,
      'trendingNotifications': trendingNotifications,
      'liveRemindersNotifications': liveRemindersNotifications,
      'sportsNotifications': sportsNotifications,
    };
  }
  //  grabbing settings state from map
  factory SettingsState.fromMap(Map<String, dynamic> map) {
    if (map == map['']) {
      return SettingsState(
        expandNavigation: map[''],
        gpsEnabled: map[''],
        celsiusEnabled: map[''],
        notificationsEnabled: map[''],
        breakingNewsNotifications: map[''],
        trendingNotifications: map[''],
        liveRemindersNotifications: map[''],
        sportsNotifications: map[''],
      );
    } else {
      return SettingsState(
        expandNavigation: map['expandNavigation'],
        gpsEnabled: map['gpsEnabled'],
        celsiusEnabled: map['celsiusEnabled'],
        notificationsEnabled: map['notificationsEnabled'],
        breakingNewsNotifications: map['breakingNewsNotifications'],
        trendingNotifications: map['trendingNotifications'],
        liveRemindersNotifications: map['liveRemindersNotifications'],
        sportsNotifications: map['sportsNotifications'],
      );
    }
  }
  // encode to a json
  String toJson() => json.encode(toMap());
  // decode the json
  factory SettingsState.fromJson(String source) =>
      SettingsState.fromMap(json.decode(source));
  //! Helps for equatable and unit testing
  @override
  List<Object?> get props => [
        expandNavigation,
        gpsEnabled,
        celsiusEnabled,
        notificationsEnabled,
        breakingNewsNotifications,
        trendingNotifications,
        liveRemindersNotifications,
        sportsNotifications,
      ];
  //! Shows changes in State for Bloc Observers
  @override
  String toString() => 'SettingsState(expandNavigation: $expandNavigation, '
      'gpsEnabled: $gpsEnabled, celsiusEnabled: $celsiusEnabled, notificationsEnabled: $notificationsEnabled,'
      'breakingNewsNotifications: $breakingNewsNotifications, trendingNotifications: $trendingNotifications,'
      ' liveRemindersNotifications: $liveRemindersNotifications, sportsNotifications: $sportsNotifications)';
}

设置Cubit 文件:

import 'dart:convert';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
part 'settings_state.dart';
//bloc/cubit for the settings screen
class SettingsCubit extends Cubit<SettingsState> with HydratedMixin {
  SettingsCubit()
      : super(SettingsState(
          expandNavigation: false,
          gpsEnabled: false,
          celsiusEnabled: false,
          notificationsEnabled: false,
          breakingNewsNotifications: false,
          trendingNotifications: false,
          liveRemindersNotifications: false,
          sportsNotifications: false,
        ));
  // Toggle for Expanding Navigation
  void toggleExpandNavigation(bool newValue) =>
      emit(state.copyWith(expandNavigation: newValue));
  // Toggle for GPS
  void toggleGpsEnabled(bool newValue) =>
      emit(state.copyWith(gpsEnabled: newValue));
  // Toggle for Celsius or Fahrenheit
  void toggleCelsiusEnabled(bool newValue) =>
      emit(state.copyWith(celsiusEnabled: newValue));
  // Toggle for All Notifications
  void toggleNotificationsEnabled(bool newValue) {
    emit(state.copyWith(notificationsEnabled: newValue));
  }
  // Toggle for Breaking News Notifications
  void toggleBreakingNewsNotifications(bool newValue) {
    emit(state.copyWith(breakingNewsNotifications: newValue));
  }
  // Toggle for Trending Notifications
  void toggleTrendingNotifications(bool newValue) {
    emit(state.copyWith(trendingNotifications: newValue));
  }
  // Toggle for Live Reminders Notifications
  void toggleLiveRemindersNotifications(bool newValue) {
    emit(state.copyWith(liveRemindersNotifications: newValue));
  }
  // Toggle for Sports Notifications
  void toggleSportsNotifications(bool newValue) {
    emit(state.copyWith(sportsNotifications: newValue));
  }
  // retrieving from phone storage - json
  @override
  SettingsState? fromJson(Map<String, dynamic> json) {
    return SettingsState.fromMap(json);
  }
  // writing to phone storage - json
  @override
  Map<String, dynamic>? toJson(SettingsState state) {
    return state.toMap();
  }
}

BLoC 测试文件:

import 'package:bloc_test/bloc_test.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/services.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:news_test_app/logic/cubit/settings_cubit.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path_provider/path_provider.dart';
import 'package:mocktail/mocktail.dart';
class MockCubit extends Mock implements SettingsCubit {}
class MockStorage extends Mock implements Storage {}
void main() {
  TestWidgetsFlutterBinding.ensureInitialized();
  group('SettingsCubit', () {
    SettingsCubit settingsCubit = SettingsCubit();
    Storage storage;
    setUp(() {
      storage = MockStorage();
      HydratedBloc.storage = storage;
      settingsCubit = SettingsCubit();
    });
    tearDown(() {
      settingsCubit.close();
    });
    blocTest<SettingsCubit, SettingsState>(
        'the cubit should emit a SettingsState(expandNavigation: true, gpsEnabled: false, celsiusEnabled: false, notificationsEnabled: false, '
        'breakingNewsNotifications: false, trendingNotifications: false, liveRemindersNotifications: false, sportsNotifications: false) '
        'when cubit.toggleExpandNavigation is called',
        build: () => settingsCubit,
        act: (cubit) => settingsCubit.toggleExpandNavigation(true),
        expect: () => [
              settingsCubit.state,
              //settingsCubit.state,
              // SettingsState(
              //   expandNavigation: false,
              //   gpsEnabled: false,
              //   celsiusEnabled: false,
              //   notificationsEnabled: false,
              //   breakingNewsNotifications: false,
              //   trendingNotifications: false,
              //   liveRemindersNotifications: false,
              //   sportsNotifications: false,
              // ),
            ]);
  });
}

控制台输出为:

package:test_api                             expect
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

None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter BLoC 测试失败 的相关文章

  • flutter 中 sqlite 中的多个参数

    我想知道如何将多个参数传递给 sqllite 中的原始查询 我的代码如下 query async get a reference to the database Database db await DatabaseHelper instan
  • 已发布的 Flutter 应用程序在启动时崩溃

    编辑 此问题的解决方案是将您的 flutter 版本升级到较新的 dev 版本 then 1 7 0 您还可以上传单独的 APK 版本 但我个人不喜欢这个选项 请确保您没有从 flutter github 开发存储库下载 错误的构建 因为那
  • 用颤动画布在形状上切一个洞

    如何使用颤动画布在形状上 切一个洞 我有一组相当复杂的形状 看起来像现实世界的物体 该物体上有一个圆角矩形形状的孔 我真的很想从形状中减去 RRect 但我找不到任何有关如何执行此操作的信息 canvas clipRRect myRRect
  • FakeAsync/tick (Async/whenStable) 与 detectorChanges()

    您能帮我区分这两件事吗 根据我的理解 如果你只使用 observable 你可以使用 detectorChanges 因此 您可以直接更改组件属性或监视服务调用并返回可观察的值 然后调用 detectorChanges 更改将在 html
  • Flutter http请求上传mp3文件

    我使用这个 api 上传 mp3 文件 使用这种方法 Future
  • Django:测试客户端的上下文在 shell 中为空

    我无法访问context的属性HttpResponse来自 ipython 的对象 但单元测试访问context 这是单元测试 测试运行正常通过 from django test import Client TestCase from dj
  • 模拟对象 - 将所有方法声明为虚拟方法还是使用接口?

    与 Java 不同 net 中的方法默认不是虚拟的 为了使用大多数模拟对象框架 您要么必须将要在模拟上使用的方法标记为 真实 对象上的虚拟方法 要么必须有一个可以模拟被测试类将使用的接口接受代替执行 将每个方法标记为虚拟似乎是一种不好的形式
  • 如何断言 Unittest 上的可迭代对象不为空?

    向服务提交查询后 我会收到一本字典或一个列表 我想确保它不为空 我使用Python 2 7 我很惊讶没有任何assertEmpty方法为unittest TestCase类实例 现有的替代方案看起来并不正确 self assertTrue
  • 如何测试 JUnit 测试的 Comparator?

    我需要测试 Compare 方法 但我对如何测试感到困惑 我可以看看该怎么做吗 public class MemberComparator implements Comparator
  • 序列化对象以进行单元测试

    假设在单元测试中我需要一个对象 其中所有 50 个字段都设置了一些值 我不想手动设置所有这些字段 因为这需要时间而且很烦人 不知何故 我需要获得一个实例 其中所有字段都由一些非空值初始化 我有一个想法 如果我要调试一些代码 在某个时候我会得
  • Cloud Functions,删除Firestore SubCollections,是否需要AdminToken?

    我正在尝试构建可调用的云函数 当用户删除帖子时 它也会尝试删除评论 这是帖子的子集合 所以我看到了这个例子并像文档示例一样实现 const admin require firebase admin const firebase tools
  • 使用cameltestsupport进行Camel单元测试,模板始终为空

    我正在用 Camel 做一个简单的单元测试 我想做的就是从文件 在资源下 读取 JSON 内容 将其发送到 Java 类进行验证 这是我试图测试的路线 无论我做什么 模板 我用来发送正文 json 始终为空 这是我的代码 public cl
  • 将 Xcode 的测试类助理编辑器与 Swift 类结合使用

    在 Xcode 中工作时 在助理编辑器中提取单元测试用例通常会很好 目前 我一直在手动选择测试文件 但我看到助理编辑器有一个选项Test Classes 我试图让这个选项自动提取我的测试文件 但我似乎无法让它工作 是否需要某种配置 它不适用
  • python 模拟第三方模块

    我正在尝试测试一些处理推文的类 我使用 Sixohsix twitter 来处理 Twitter API 我有一个类充当 Twitter 类的外观 我的想法是模拟实际的 Sixohsix 类 通过随机生成新推文或从数据库检索它们来模拟推文的
  • 如何在 pytest 中将单元测试和集成测试分开

    根据维基百科 https en wikipedia org wiki Unit testing Description和各种articles https techbeacon com devops 6 best practices inte
  • 使用鼻子获取设置中当前测试的名称

    我目前正在使用鼻子编写一些功能测试 我正在测试的库操作目录结构 为了获得可重现的结果 我存储了一个测试目录结构的模板 并在执行测试之前创建该模板的副本 我在测试中执行此操作 setup功能 这确保了我在测试开始时始终具有明确定义的状态 现在
  • 如何仅添加一个BottomNavigationBarItem

    我有一个 BottomNavigationBar 我只需要在其中添加一个集中按钮 但我收到此错误 package flutter src material bottom navigation bar dart 断言失败 第 191 行 po
  • 由于主项目复杂的 lib-project 依赖关系,Jenkins 服务器上的自动化 Android UI 测试失败

    简单总结一下 我的项目结构如下 A and B是 android lib projects 其中B依赖于取决于A C 普通的android项目 取决于B T是测试项目C 我的詹金斯服务器上相应地有两个项目 一个用于C和一个用于T 它们有自己
  • 使用 Firestore 和 Flutter 填充数据表(使用 StreamBuilder)

    如何使用 StreamBuilder 填充数据表 下面是我的代码 new StreamBuilder stream widget returnStreamWithActiveKeysOnly builder BuildContext con
  • pytest:同一接口的不同实现的可重用测试

    想象一下我已经实现了一个名为的实用程序 可能是一个类 Bar在一个模块中foo 并为其编写了以下测试 测试 foo py from foo import Bar as Implementation from pytest import ma

随机推荐