2

用mockito测试riverpod的正确方法是什么?

运行上面的代码,


/// ### 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>()]);
    });
  });
}

运行测试返回

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>

我是riverpod的新手,显然我错过了一些我试图遵循的东西

4

3 回答 3

4

我发现我在使用StateNotifierProvider. 诀窍是不仅要覆盖 StateNotifierProvider,还要覆盖它的state属性(它是一个 StateNotifierStateProvider 对象)。

class SomeState {
  final bool didTheThing;
  SomeState({this.didTheThing = false});
}

class SomeStateNotifier extends StateNotifier<SomeState> {
  SomeStateNotifier() : super(SomeState());

  bool doSomething() {
    state = SomeState(didTheThing: true);
    return true;
  }
}

final someStateProvider = StateNotifierProvider<SomeStateNotifier>((ref) {
  return SomeStateNotifier();
});

class MockStateNotifier extends Mock implements SomeStateNotifier {}

void main() {
  final mockStateNotifier = MockStateNotifier();
  when(mockStateNotifier.doSomething()).thenReturn(true);

  final dummyState = SomeState(didTheThing: true); // This could also be mocked

  ProviderScope(
    overrides: [
      someStateProvider.overrideWithValue(mockStateProvider), // This covers usages like "useProvider(someStateProvider)"
      someStateProvider.state.overrideWithValue(dummyState),  // This covers usages like "useProvider(someStateProvider.state)"
    ],
    child: MaterialApp(...),
  );
}
于 2021-02-09T15:57:20.147 回答
1

还可以考虑通过在顶级 ProviderScope 中使用 Override 来模拟各种提供程序。这就是覆盖可以做得很好的事情。

于 2020-12-15T01:18:04.767 回答
1

您的代码中有 2 个错误

您正在尝试测试 throw 错误,因此您应该使用thenThrow而不是thenAnswer,但是因为您要覆盖混合方法,所以我建议您不要使用Mockuse Fake(来自同一个 mockito 库)来覆盖方法,然后根据需要抛出它

class MockDelegate extends Fake implements FutureDelegate<String> {

  @override
  Future<String> call() async {
    throw NullThrownError; //now you can throw whatever you want
  }
}

第二个问题(也是你的代码警告你的问题)是你故意抛出,所以你应该期待一个 AsyncError 代替,所以调用container.read(stringProvider).data.value是一个错误,因为阅读riverpod文档:

调用数据时:

当前数据,如果在加载/错误中,则为 null。

因此,如果您期望出现错误(AsyncError)数据为空,并且因为调用data.value它与写入相同,null.value这就是您遇到的错误

这是您可以尝试的代码:

class MockDelegate extends Fake implements FutureDelegate<String> {
  @override
  Future<String> call() async {
    throw NullThrownError;
  }
}

void main() {
  group('`stringProvider`', () {
    final _delegate = MockDelegate();
    test('WHEN `delegate` throws THEN `provider`return exception', () async {

      final container = ProviderContainer(
        overrides: [
          stringProvider
              .overrideWithProvider(FutureProvider((ref) => _delegate.call()))
        ],
      );

      expect(container.read(stringProvider), const AsyncValue<String>.loading());

      container.read(stringProvider).data.value;

      await Future<void>.value();
      expect(container.read(stringProvider), isA<AsyncError>()); // you're expecting to be of type AsyncError because you're throwing
    });
  });
}
于 2020-12-14T18:15:50.997 回答