如何在Dart中测试使用期货的代码

时间:2019-04-01 16:53:23

标签: dart

我正在为我的Flutter应用程序使用Redux架构。我想做一些集成测试。我想将一些操作发送到存储中,并验证其状态是否正确。

应用程序对http请求使用中间件,并且Future.value模拟了http调用。

基本上,我有类似以下内容。我的中间件:

typedef Authenticator = Future<AuthToken> Function(AuthCode code);

//we can send mocked implementation for auth request.
Middleware<AppState> provideAuthMiddleware({Authenticator authenticator = _authenticator}) {
  Future<void> authMiddleware(Store<AppState> store, dynamic action, NextDispatcher next) async {
    next(action);
    if (action is AuthCodeReceiveAction) {
        final token = await authenticator(action.code);
        store.dispatch(AuthFailAction(AuthCodeFailedError(e)));
    }
  }
  return authMiddleware;
}

测试具有以下结构:

test('when can exchange code for token', () {
  Future<AuthToken> mockedAuth(AuthCode code) {
    return Future.value(const AuthToken('Success'));
  }

  final store = Store<AppState>(
    appReducer,
    initialState: const AppState.initial(),
    middleware: [
      provideAuthMiddleware(authenticator: mockedAuth),
    ],
  );

  store.dispatch(const AuthCodeReceiveAction(AuthCode('rawValue')));
  expect(store.state, <check it is autorized>); //The state is not yet correct.
});

问题是await authenticator(action.code);在微任务队列中完成。因此在检查过程中商店的状态不正确。

执行该检查的正确方法是什么?官方文档建议如下:

expect(new Future.value(10), completion(equals(10)));

但是我无法访问未来。我不想添加黑客 等待Future.value(0);在expect函数之前。

0 个答案:

没有答案