5

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

我有 bloc 类和小部件工作,但我不知道如何测试小部件。我正在使用BlocProvider文章中描述的 a ,但我不知道如何为小部件提供模拟的 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,但我不知道该怎么做。我想确保小部件按预期运行。

4

2 回答 2

1

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

编码前

请注意,在抽取小部件时,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
        ),
      ));
    }

于 2019-06-28T14:49:05.787 回答
0

在此示例中,您使用BlocProvider来获取您的ProfileBloc,但您可以直接使用final ProfileBloc profileBloc = ProfileBloc;. 使用外部集团应该不重要,因为这是在小部件测试之后。

于 2018-11-26T23:12:16.623 回答