简体   繁体   中英

Flutter/Dart unit tests with app localization

I am trying to write unit tests in Dart/Flutter for my TextField validations. However, I have a little problem here because the tests are working, but I want to return the value with localization now.

How exactly do I implement this into the tests now?

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class ValidationConstants {
  static String? notEmpty(String? value, BuildContext context) {
    if (value == null || value.isEmpty) {
      return AppLocalizations.of(context)!.text_field_can_not_be_empty;
    }
    return null;
  }
}


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

void main() {


  group('text field validations', () {
    test('no empty text validation', () {
      const emptyText = '';
      const noEmptyText = 'Hello, World!';

      // BuildContext is needed here
      expect(ValidationConstants.notEmpty(emptyText, [...]).runtimeType, String);
      expect(ValidationConstants.notEmpty(noEmptyText, [...]) == null, true);
    });
  });
}

You can use like below, use setUp() method provided by flutter_test

 void main() {
  S? mockAppLocal;

  setUp(() async {
    mockAppLocal = await S.delegate.load(const Locale('en'));
  });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM