问题描述
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()),),);
}
}
您可能希望在测试后删除注释。