2

I want to write a test for a user_data dart file. I want to check if data has been successfully written into the json file through an effective test.

@JsonSerializable()
class UserData {
  UserData({
    this.id,
    this.createdAt,
    this.defaultLanguage,
    this.defaultSchool,
  });

  factory UserData.fromJson(Map<String, dynamic> json) =>
      _$UserDataFromJson(json);

  final String? id;
  final DateTime? createdAt;
  final String? defaultLanguage;
  final School? defaultSchool;
}

Can anyone help to generate a unit test for the above dart code? Thank you!

Annie Box
  • 31
  • 3

1 Answers1

2

I'm not entirely sure what you mean but I think you want to make sure that your deserialization works, right?

void main (){
   late Map<String,dynamic> json;

   setUp(() {
     json = {
      id : yourIDData,
      createdAt : yourDateData,
      defaultLanguage : yourLanguageData,
      defaultSchool : yourSchoolData,
      };
    });

    test('object has correct properties', () {
      final userData = UserData.fromJson(json);
      expect(userData.id, yourIDData);
      expect(userData.createdAt, yourDateData);
      expect(userData.defaultLanguage, yourLanguageData);
      expect(userData.defaultSchool, yourSchoolData);
    });
}
Christian
  • 834
  • 7
  • 18
  • Yes, I want to ensure that my serialization and deserialization work well. Should I parse JSON to a model and test it? I try the code you shared, it seems doesn't work. Could you please give it a look and see if there is any error or bug? Thanks! – Annie Box Mar 24 '22 at 06:24
  • I have edited the json, should work now. – Christian Mar 24 '22 at 08:51