gpt4 book ai didi

unit-testing - 使用 BLoC 模式测试小部件

转载 作者:IT老高 更新时间:2023-10-28 12:42:16 25 4
gpt4 key购买 nike

我一直在学习 Flutter/Dart 和 BLoC 模式。我以这篇文章为出发点: https://www.didierboelens.com/2018/08/reactive-programming---streams---bloc/

我有 bloc 类和小部件工作,但我不知道如何测试小部件。我正在使用文章中描述的 BlocProvider,但我不知道如何为小部件提供模拟的 bloc 类。

如果我有这样的代码:

@override
Widget build(BuildContext context) {
final ProfileBloc profileBloc = BlocProvider.of<ProfileBloc>(context);

return Scaffold(
body: Container(
child: StreamBuilder<AuthModel>(
stream: profileBloc.outAuthModel,
initialData: null,
builder: (BuildContext context, AsyncSnapshot<AuthModel> snapshot) {
if (snapshot.hasData) {
return buildProfilePage(context, snapshot.data.profile);
}
return buildStartPage();
},
),
));
}

我想模拟我的 ProfileBloc,但它是在我的 build() 函数中创建的,并且需要上下文。如何测试这个小部件?我想我需要一种方法来传递一个模拟的 ProfileBloc,但我不知道该怎么做。我想确保小部件按预期运行。

最佳答案

我在测试小部件时遇到了完全相同的问题并且能够解决它。这是不起作用的“代码前”和成功的“代码后”......

代码之前

请注意,在抽取小部件时,MaterialApp 被设置为最顶部的小部件。

Future<Null> _buildRideCard(WidgetTester tester) async {
await tester.pumpWidget(MaterialApp( // top most widget
localizationsDelegates: [
AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
//some other stuff, irrelevant for this example

));
}

代码之后

注意 MaterialApp 小部件现在是如何用 BlocProvider 包装的,它的 blocProviders 属性给出了小部件测试所需的 Bloc 列表。这解决了我的问题,现在我的小部件测试中的 bloc 没有任何上下文问题。希望对您有所帮助;)

Future<Null> _buildRideCard(WidgetTester tester) async {
await tester.pumpWidget(BlocProviderTree( // <- magic #1
blocProviders: [ <- magic #2
BlocProvider<RideDetailsBloc>(
bloc: RideDetailsBloc(_setupRidesRepo()))
],
child: MaterialApp(
localizationsDelegates: [
AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
//some other stuff, irrelevant for this example
),
));
}

关于unit-testing - 使用 BLoC 模式测试小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53489915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com