'Mockito dont follow 'when()' behavior (Dart/Flutter)

I'm trying to do unit tests, but mockito does not follow the behavior of 'when()' and returns a fake value from the generated code

when from test:

  when(MockHttp.post(any)).thenAnswer(
      (_) => Future.value(ReturnClass(data: {
        'access_token': 'acess',
        'token_type': 'token_type',
        'expires_in': DateTime.now().add(Duration(hours: 1)).hour,
        'scope': 'scope'
      }, error: null, status: 0)),
    );

Mock generated class:

  _i6.Future<_i2.ReturnClass> post(String? path,
          {Map<String, dynamic>? body,
          Map<String, dynamic>? params,
          Map<String, String>? headers}) =>
      (super.noSuchMethod(
          Invocation.method(
              #post, [path], {#body: body, #params: params, #headers: headers}),
          returnValue: Future<_i2.JdApiResponseDto>.value(
              _FakeReturnClass_0())) as _i6.Future<_i2.ReturnClass>);

In the real function the return value is '_FakeReturnClass_0' instead of ReturnClass from 'when()' I don't know why this is happening :(

Edit:

basically this is the test:

setUpAll(() {
  when(service.post(any)).thenAnswer(
        (_) => Future.value(
         ReturnClass(data: {
          'access_token': 'acess',
          'token_type': 'token_type',
          'expires_in': DateTime.now().add(Duration(hours: 1)).hour,
          'scope': 'scope'
        }, error: null, status: 0)),
      );
} 
group('Test Repository Token', () {
    test('getToken should not let token be null', () async {
    
      await _repository.getToken();

      expect(_repository.token, isNotNull);
    }); 
  });

and that is my real function (it passes the mock of httpbut still not entering 'when()')

try {
        var response = await http.post(
          api.authUrl ?? '',
          params: {
            'grant_type': api.grantType,
            'client_id': api.clientId,
            'client_secret': api.clientSecret,
          },
          // headers: {
          //   IService.contentTypeHeader:
          //       IService.formUrlEncodedContentType,
          // },
        );
} catch (e) {
        print('Token Error:');
        print(e);
      }

and when I test the real function there is a error because the mock is returning for the response the '_FakeReturnClass_0()' instead of ReturningClass that i put on the 'when()' in the setup of the test



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source