You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter测试报错:获取电视推荐成功时未正确更新状态

Flutter测试失败:Televisi推荐数据断言不匹配及其他测试错误

我是Flutter初学者,正在学习测试,运行项目时遇到3个测试错误,其中一个具体报错如下:

C:\src\flutter\bin\cache\dart-sdk\bin\dart.exe test C:\Expert1\ditonton-master-main\test\presentation\provider\televisi_provider\televisi_detail_notifier_test.dart -p vm --plain-name 'Get Televisi Recommendations should get data from the use case'   
04:51 +169 -4: C:\Expert1\ditonton-master-main\test\presentation\provider\televisi_provider\televisi_detail_notifier_test.dart: Get Televisi Recommendations should update recommendation state when data is gotten successfully [E]
    Actual: [
              Televisi:Televisi(2000-09-09 09:09:09.591918, backdropPath, [1, 2, 3], 1, original_name, overview, 1.0, posterPath, [origin_country, origin_country], name, original_language, 1.0, 1)
            ]

  package:test_api                                                                        expect
  package:flutter_test/src/widget_tester.dart 460:16                                      expect
  test\presentation\provider\televisi_provider\televisi_detail_notifier_test.dart 141:11  main.<fn>.<fn>

解决步骤:

  1. 修复Televisi类的相等性判断
    Dart自定义类默认用引用地址判断相等,即使属性完全一致,不同实例也会被判定为不相等。需要重写==运算符和hashCode方法:

    class Televisi {
      // 你的类属性定义...
    
      @override
      bool operator ==(Object other) =>
          identical(this, other) ||
          other is Televisi &&
              runtimeType == other.runtimeType &&
              id == other.id &&
              name == other.name &&
              backdropPath == other.backdropPath &&
              originCountry == other.originCountry;
    
      @override
      int get hashCode =>
          id.hashCode ^
          name.hashCode ^
          backdropPath.hashCode ^
          originCountry.hashCode;
    }
    
  2. 核对测试预期值与实际返回值
    打开televisi_detail_notifier_test.dart第141行,检查expect语句中的预期Televisi列表,确保每个对象的属性(比如时间格式、数组元素顺序和内容)与测试用例中模拟返回的实际值完全匹配。

  3. 检查测试用例的模拟逻辑
    确认测试中模拟获取推荐数据的用例是否正确返回了符合预期的Televisi对象,有没有属性赋值错误或遗漏。

  4. 排查其他两个测试错误
    重复上述思路:检查对应测试类的相等性实现、断言的预期值与实际值是否匹配、模拟逻辑是否正确。

内容的提问来源于stack exchange,提问作者alu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 09:15:32