所以我有一个简单的计数器应用程序,
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
。我们甚至应该测试状态吗?
答案 0 :(得分:1)
首先需要在使用state
方法时指定类型以避免编译错误:
final _CounterAppState state = tester.state(find.byKey(key));
其次,_CounterAppState
和 _counter
是私有的,您不应直接测试私有类/变量。您可以将类设为公开并为私有变量提供一个公共 getter:
int get testCounter => _counter;
但是,有一种方法可以访问我不推荐的私有声明。使用 @visibleForTesting
注释您的私有变量/类将使其公开以使代码可测试。不要忘记导入基础或元库。
用于注释公开的声明,以便它 比其他必要的更明显,使代码可测试。
分析器等工具可以提供反馈
这是实现:
// 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()),
),
);
}
}
您可能希望在测试后删除注释。