Home > Mobile >  Getting the common "null check operator on a null value" when testing using Chopper client
Getting the common "null check operator on a null value" when testing using Chopper client

Time:08-22

I'm testing my repository code that use Chopper, and am now getting the below errors, that isn't in my code:

Null check operator used on a null value package:chopper/src/interceptor.dart 195:58 HttpLoggingInterceptor.onResponse package:chopper/src/base.dart 215:23 ChopperClient._interceptResponse package:chopper/src/base.dart 346:17 ChopperClient._processResponse package:chopper/src/base.dart 341:12
ChopperClient.send

I've created a static method that return my own chopper service as follows:

  static MyChopperService create(String baseUrl, [http.Client? client]) {
    return _$MyChopperService (
      ChopperClient(
        baseUrl: baseUrl,
        client: client,
        services: [_$MyChopperService ()],
        interceptors: [
              HttpLoggingInterceptor(),
              CurlInterceptor(),
        ],
        converter: const JsonConverter(),
      ),
    );
  }

In my unit tests I create the service as follows:

  final MockClient mockClient = MockClient((req) async => Response('return data', 200));
  final MyChopperService service = MyChopperService.create('baseUrl', client: mockClient);
  ... then I go ahead and use this calling my repository.

Any ideas what I'm doing wrong?

CodePudding user response:

Based on what I can see, you have two options:

  1. When creating the Response in the MockClient, also add a Request object that carries the Uri/Url. That is missing which seems to be something that the Chopper library haven't guarded against.

Edit: Meaning you could do something like this:

Response('return data', 200, request: Request('GET', Uri(scheme: 'https', host: 'test.dev')))
  1. Let your service-creator take in interceptors as an argument and pass none into it when running your tests. That way the code causing the error won't be executed.

So change the method signature to instead have this:

{http.Client? client, List<dynamic>? interceptors}

and use this in the ChopperClient constructor:

interceptors: interceptors ??
[
    HttpLoggingInterceptor(),
    CurlInterceptor(),
],

Then call it in your test like this:

MyChopperService.create('baseUrl', client: mockClient, interceptors: []);
  • Related