Home > Enterprise >  How I get a TypeObject Error in dart test
How I get a TypeObject Error in dart test

Time:11-30

Im trying to create a test for get a error in type convertion

  modelTest = VersionModel(
        forceUpdate: true,//bool
        buildNumber: 1222,//int
        versionNumber: "2",//String
      );

My json that has a wrong type in the object

 final jsonError = {
      "force_update": "false",
      "build_number": 31003.,
      "version_number": "3.1.0"
    };

My test

 test("Should be return instance of VersionModel from json", () {
      final json = modelTest!.toJson();
      expect(VersionModel.fromJson(json),
         Exception());
    });

message: type 'String' is not a subtype of type 'bool?' in type cast

What I tryed

 test("Should be return an error of a instance VersionModel to json",
        () {
      try {
        VersionModel.fromJson(jsonError);
      } catch (e) {
        expect(e, isInstanceOf<TypeError>());
      }

CodePudding user response:

You can test the error like this. The error in the serialisation will be caught and throws exception as follows. Then it will check the type which was thrown at serialisation and match with the excepted value.

    test("Should be return instance of VersionModel from json", () {
    expect(() {
      try {
        VersionModel.fromJson(jsonEncode(jsonError));
      } catch (e) {
        throw Exception();
      }
    }, throwsA(isA<Exception>()));
  });

According to this It will throws an exception for the all error types that comes from the json.

  • Related