微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在颤振中测试状态? visibleForTesting top-level constant

如何解决如何在颤振中测试状态? visibleForTesting top-level constant

所以我有一个简单的计数器应用程序,

class Counterapp extends StatefulWidget {
  const Counterapp({Key? key}) : super(key: key);

  @override
  _CounterappState createState() => _CounterappState();
}

class _CounterappState extends State<Counterapp> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onpressed: _incrementCounter,tooltip: 'Increment',child: Text(_counter.toString()),),);
  }
}

那么我如何测试 _counter 状态?

我试过这样做,

testWidgets("counter",(tester) async {
  const key = Key("counter");
  await tester.pumpWidget(const Counterapp(key: key));

  final state = tester.state(find.byKey(key));

  expect(state._counter,0);
});

但我收到错误 Error: The getter '_counter' isn't defined for the class。我们甚至应该测试状态吗?

解决方法

首先需要在使用state方法时指定类型以避免编译错误:

final _CounterAppState state = tester.state(find.byKey(key));

其次,_CounterAppState_counter 是私有的,您不应直接测试私有类/变量。您可以将类设为公开并为私有变量提供一个公共 getter:

int get testCounter => _counter;

但是,有一种方法可以访问我不推荐的私有声明。使用 @visibleForTesting 注释您的私有变量/类将使其公开以使代码可测试。不要忘记导入基础或元库。

visibleForTesting top-level constant

用于注释公开的声明,以便它 比其他必要的更明显,使代码可测试。

分析器等工具可以提供反馈

  • 该注解与不在包的 lib 文件夹中的声明、私有声明或在 未命名的静态扩展名,或
  • 声明在其定义库或定义包的测试文件夹中的库之外被引用。

这是实现:

// Import the foundation library
import 'package:flutter/foundation.dart';

class CounterApp extends StatefulWidget {
  const CounterApp({Key? key}) : super(key: key);

  @override
  _CounterAppState createState() => _CounterAppState();
}

// Add the annotation above the class
@visibleForTesting
class _CounterAppState extends State<CounterApp> {
  // Add the annotation above the variable
  @visibleForTesting
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,tooltip: 'Increment',child: Text(_counter.toString()),),);
  }
}

您可能希望在测试后删除注释。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。