How can test if data has been written into a json successfully in Flutter and Dart?

1.5k views Asked by At

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!

1

There are 1 answers

2
Christian On

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);
    });
}