Flutter单元测试题,如何测试局部变量变?

dphi5xsq  于 2023-08-07  发布在  Flutter
关注(0)|答案(2)|浏览(138)
/// A flag that indicates whether the NotificationProvider is being processed.
  bool _isProcess = false;

  set isProcess(bool value) {
    _isProcess = value;
    notifyListeners();
  }

  bool get isProcess => _isProcess;

  NotificationProvider({required this.fetchNotificationUseCase});

  //TODO("Satoshi"): catch exception or error
  /// Fetch notification from api-server.
  Future<void> fetchNotification() async {
    try {
      isProcess = true;
      final res = await fetchNotificationUseCase.fetchNotification();

      notificationList.clear();
      notificationList.addAll(res);

      isProcess = false;
      notifyListeners();
    } catch (e) {
      isProcess = false;
      notifyListeners();
      debugPrint(e.toString());
    }
  }

字符串
我想测试isProcess属性是否更改为true和false。但是我唯一能测试的是在fetchNotification方法完成后isProcess是否为false。如何测试isProcess的变化?
这是我写的测试代码

test('then isProcess is being false', () async {
    await notificationProvider.fetchNotification();

    expect(notificationProvider.isProcess, false);
  });

blmhpbnm

blmhpbnm1#

您可以使用ChangeNotifier中的addListener方法查看值的变化。
样本码

test('isProcess changes true then false', () async {
  expect(notificationProvider.isProcess, false);
  int listenerCounts = 0;
  List<bool> matches = [true, false];
  final listener = () {
    expect(notificationProvider.isProcess, matches[listenerCounts]);
    listenerCounts++;
  }
  notificationProvider.addListener(listener);
  await notificationProvider.fetchNotification();
  notificationProvider.removeListener(listener);
});

字符串

envsm3lx

envsm3lx2#

fetchNotification在执行异步工作之前同步设置isProcess = true。因此,您可以同步检查notificationProvider.isProcessfalse转换到true,然后检查它在所有异步工作完成后返回到false

test('then isProcess is being false', () async {
    expect(notificationProvider.isProcess, false);
    var future = notificationProvider.fetchNotification();
    expect(notificationProvider.isProcess, true);
    await future;
    expect(notificationProvider.isProcess, false);
  });

字符串

相关问题