在Flutter中测试本地化字符串

时间:2018-11-29 12:03:40

标签: testing internationalization widget flutter

当我尝试测试包含的小部件

 hintText: LocalizationResources.of(context).writecomment

我看到一个异常:

The following NoSuchMethodError was thrown building CommentInput(dirty, state:
_CommentInputState#32224):
The getter 'writecomment' was called on null.

那么,我缺少什么吗? 小部件可以在设备和模拟器上很好地构建。

这是我的测试结果:

....
 final Widget widget =
        MaterialApp(home: CommentWallWidget(channelUid: '123456'), title: 'jelena',);

    await tester.pumpWidget(widget);

LocalizationResources只是简单的l10n:

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import 'l10n/messages_all.dart';

///class containing localization logic and string getters
class LocalizationResources {
  static Future<LocalizationResources> load(Locale locale) {
    final String name =
        locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
    final String localeName = Intl.canonicalizedLocale(name);

    return initializeMessages(localeName).then((_) {
      Intl.defaultLocale = localeName;
      return LocalizationResources();
    });
  }

  static LocalizationResources of(BuildContext context) {
    return Localizations.of<LocalizationResources>(
        context, LocalizationResources);
  }
....

1 个答案:

答案 0 :(得分:0)

您需要将测试小部件包装在MediaQuery小部件中,并提供本地化委托。有关更多示例,请参见here

final Widget widget = MediaQuery(
  data: MediaQueryData(),
  child: MaterialApp(
    localizationsDelegates: [LocalizationResourcesDelegate()],
    home: CommentWallWidget(channelUid: '123456'),
    title: 'jelena',
  )
);