【问题标题】:How to test state in flutter?如何在颤振中测试状态?
【发布时间】:2021-09-21 11:56:17
【问题描述】:

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

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。我们甚至应该测试状态吗?

【问题讨论】:

    标签: flutter flutter-test


    【解决方案1】:

    首先,您需要在使用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()),
          ),
        );
      }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 2021-07-22
      • 2021-08-17
      • 2020-06-12
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多