1

我正在尝试创建一个反应式SharedPreferences实用程序,但我遇到了这个问题。这是我的课

class SPUtil {
    final _workoutsStreamController = StreamController<
          Result<Iterable<PreferencesWorkout>, Exception>>.broadcast();

    @override
    Stream<Result<Iterable<PreferencesWorkout>, Exception>> getWorkouts() async* {
      final prefs = await SharedPreferences.getInstance();
      _workoutsStreamController.sink.add(success(_getStoredWorkouts(prefs)));
      yield* _workoutsStreamController.stream;
    }
}

这是我的测试

test("getWorkouts SHOULD return empty list WHEN nothing is stored",
        () async {
      SharedPreferences.setMockInitialValues({});

      final actual = await _sut.getWorkouts().first;

      expect((actual as Success).value, []);
    });

每当我运行此测试时,它都会循环 30 秒并返回此错误

dart:async  _startMicrotaskLoop

TimeoutException after 0:00:30.000000: Test timed out after 30 seconds. See https://pub.dev/packages/test#timeouts

如果我改用这个实现,一切都很好

class SPUtil {
    @override
    Stream<Result<Iterable<PreferencesWorkout>, Exception>> getWorkouts() async* {
      final prefs = await SharedPreferences.getInstance();
      yield success(_getStoredWorkouts(prefs));
    }
}

所以我假设我的测试是正确的。提前致谢。

4

1 回答 1

2

我终于找到了问题,StreamController如果不听就不会发出任何东西,因此测试会超时。

test("getWorkouts SHOULD return empty list WHEN nothing is stored",
        () async {
      SharedPreferences.setMockInitialValues({});

      final actual = _sut.getWorkouts().first;      
      actual.listen((event) {});

      final actualResult = await actual;
      expect((actualResult as Success).value, []);
    });
于 2020-05-20T23:34:39.877 回答