Gaurav Swarankar
Gaurav Swarankar

Reputation: 19

Unit testing for Exception in flutter

i'm trying to pass my unit test in flutter. i'm getting my expected value and actual value still my test got failed.

This is my Method in BaseApi class.

Exception getNetErrorException(String url) => HttpException(url);

and this is my test :

group("getNetErrorException", () {
  test("Should throw a HttpException when there is an error", () {
    BaseApi api = BaseApi();
    expect(api.getNetErrorException(""), HttpException(""));
  });
});

Upvotes: 1

Views: 1576

Answers (1)

jamesdlin
jamesdlin

Reputation: 89946

There's no way for expect to tell if one HttpException('') is "equal" to another HttpException('') unless HttpException overrides operator==, which it doesn't do. The default operator == that it inherits from Object tests for object identity.

You'd need to do:

expect(api.getNetErrorException(''), isA<HttpException>());

or if you must test the error message, you could create a custom matcher to check it:

expect(
  HttpException(''),
  allOf(
    isA<HttpException>(),
    predicate<HttpException>(
      (httpException) => httpException.message == ''),
  ),
);

Upvotes: 1

Related Questions