I would like to do the unit test for model by Flutter. Then I want to use test json data.
But I got the error message.
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast
I want to know how to solve this issue.
Here is the test codes.
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);
});
});
}
Here is the model
@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);
}
And this is the test data.
[
{
"id": 999,
"name": "testest",
"amount": 30000,
"image": {
"id": 9999,
"image": {
"url": "https://text.jpg",
},
},
}
]
CodePudding user response:
Your json file is a list, not an object, either you change your json file in
{
"id": 999,
"name": "testest",
"amount": 30000,
"image": {
"id": 9999,
"image": {
"url": "https://text.jpg",
},
},
}
Or you will need to update your code to take the first element of the list:
final file = File('json/gift_test.json').readAsStringSync();
final gifts = Gift.fromJson((jsonDecode(file) as List).first as Map<String, dynamic>);