dimanche 13 décembre 2020

what is the correct approach to test riverpod with mockito

what is the correct approach to test riverpod with mockito?

running the code above,


/// ### edited snippets from production side ###
/// not important, skip to the TEST below!

/// this seems meaningless just because it is out of context
mixin FutureDelegate<T> {
  Future<T> call();
}

/// delegate implementation

import '../../shared/delegate/future_delegate.dart';

const k_STRING_DELEGATE = StringDelegate();

class StringDelegate implements FutureDelegate<String> {
  const StringDelegate();
  @override
  Future<String> call() async {
   /// ... returns a string at some point, not important now
  }
}



/// the future provider
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '<somewhere>/delegate.dart'; /// the code above

final stringProvider = FutureProvider<String>((ref) => k_STRING_DELEGATE());

/// ### edited snippets from TEST side ###


/// mocking the delegate
import 'package:mockito/mockito.dart';
import '<see above>/future_delegate.dart';

class MockDelegate extends Mock implements FutureDelegate<String> {}


/// actual test 
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/all.dart';
import 'package:mockito/mockito.dart';
import '<somewhere in my project>/provider.dart';
import '../../domain/<somewhere>/mock_delegate.dart'; // <= the code above

void main() {
  group('`stringProvider`', () {
    final _delegate = MockDelegate();
    test('WHEN `delegate` throws THEN `provider`return exception',
        () async {
      when(_delegate.call()).thenAnswer((_) async {
        await Future.delayed(const Duration(seconds: 1));
        throw 'ops';
      });

      final container = ProviderContainer(
        overrides: [
          stringProvider
              .overrideWithProvider(FutureProvider((ref) => _delegate()))
        ],
      );
      expect(
        container.read(stringProvider),
        const AsyncValue<String>.loading(),
      );
      await Future<void>.value();
      expect(container.read(stringProvider).data.value, [isA<Exception>()]);
    });
  });
}

running the test returns

NoSuchMethodError: The getter 'value' was called on null.
  Receiver: null
  Tried calling: value
  dart:core                                Object.noSuchMethod
  src/logic/path/provider_test.dart 28:48  main.<fn>.<fn>

I'm new to riverpod, clearly I'm missing something I tried to follow this

Aucun commentaire:

Enregistrer un commentaire