如何在颤振中测试状态?

时间:2021-07-12 09:52:01

标签: flutter flutter-test

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

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

1 个答案:

答案 0 :(得分: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()),
      ),
    );
  }
}

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