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

677

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);
    });
}
Share:
677
Annie Box
Author by

Annie Box

Updated on December 01, 2022

Comments

  • Annie Box
    Annie Box 12 months

    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!

    • Christian H
      Christian H over 1 year
      Please provide the test you wrote and the following output.
  • Annie Box
    Annie Box over 1 year
    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!
  • Christian
    Christian over 1 year
    I have edited the json, should work now.