在 Flutter 单元测试中使用 Json 数据文件

Use Json data file on Flutter unit test

我想通过 Flutter 对模型进行单元测试。 然后我想用test json data.

但是我收到了错误消息。
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast

我想知道如何解决这个问题。

这是测试代码。

void main() {
  group('Gift Test', () {
    test('Gift model test', () {
      final file = File('json/gift_test.json').readAsStringSync();
      final gifts = Gift.fromJson(jsonDecode(file) as Map<String, dynamic>);

      expect(gifts.id, 999);
    });
  });
}

这是模型

@freezed
abstract class Gift with _$Gift {
  @Implements(BaseModel)
  const factory Gift({
    int id,
    String name,
    int amount,
    Image image,
  }) = _Gift;

  factory Gift.fromJson(Map<String, dynamic> json) => _$GiftFromJson(json);
}

这是测试数据

[
  {
    "id": 999,
    "name": "testest",
    "amount": 30000,
    "image": {
      "id": 9999,
      "image": {
        "url": "https://text.jpg",
      },
    },
  }
]

您的 json 文件是一个列表,而不是一个对象,您可以在

中更改 json 文件
  {
    "id": 999,
    "name": "testest",
    "amount": 30000,
    "image": {
      "id": 9999,
      "image": {
        "url": "https://text.jpg",
      },
    },
  }

或者您需要更新代码以获取列表的第一个元素:

final file = File('json/gift_test.json').readAsStringSync();
final gifts = Gift.fromJson((jsonDecode(file) as List).first as Map<String, dynamic>);