这里的新手程序员刚开始颤振并尝试探索颤振测试。以下是我的userInfoProvider代码;
import 'package:flutter/cupertino.dart';
class UserInfoProvider with ChangeNotifier{
String _username;
String _userRole;
getUsername() => _username;
getUserRole() => _userRole;
setUsername(String username){
_username = username;
notifyListeners();
}
setUserRole(String userRole){
_userRole = userRole;
notifyListeners();
}
getCurrentUserInformation(String uid) async {
Query q = await Firestore.instance
.collection('users')
.document(uid)
.get()
.then((DocumentSnapshot ds) {
setUsername(ds.data['userName']);
setUserRole(ds.data['userRole']);
return;
});
}
}
我有一个具有Uid属性的主页窗口小部件。此小部件使用此uid从firestore中的“用户”集合中进行标识,以将用户名和userRole设置为UserInfoProvider。
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'UserInfoProvider.dart';
class HomePage extends StatefulWidget {
final String uid;
HomePage(this.uid);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
void afterFirstLayout(BuildContext context) async {
var user = Provider.of<UserInfoProvider>(context);
await user.getCurrentUserInformation(widget.uid);
}
@override
Widget build(BuildContext context) {
return Container();
}
}
SecondPage小部件具有2个文本小部件,用于显示UserInfoProvider get方法中的用户名和userRole。
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'UserInfoProvider.dart';
class SecondPage extends StatefulWidget {
@override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
@override
Widget build(BuildContext context) {
final user = Provider.of<UserInfoProvider>(context);
return Column(
children: <Widget>[
Text(user.getUsername()),
Text(user.getUserRole())
],
);
}
}
在这种情况下,如何编写小部件测试,从而我想测试SecondPage小部件以确保显示的文本(例如userRole)与我在HomePage小部件中构建的模拟Uid相同?以下是我的测试代码,未通过测试;
testWidgets("Test secondpage widget to display correct userRole", (WidgetTester tester) async{
final uid = "ekkMH1sKW1dN0r3ZTQGCngJS1cV2";
await tester.pumpWidget(ChangeNotifierProvider(
builder: (_) => UserInfoProvider(),
child: MaterialApp(
home: HomePage(uid)
)
));
await tester.pumpWidget(ChangeNotifierProvider(
builder: (_) => UserInfoProvider(),
child: MaterialApp(
home: SecondPage()
)
));
final UserRoleTextFinder = find.text("someUserRole");
expect(UserRoleTextFinder, findsOneWidget);
});
我想我是根据我的测试代码构建了两个userInfoProvider实例,这些实例的Homepage状态与SecondPage的状态不同?无论如何,我对我的情况有任何建议。