Flutter 中提供者的单元测试

Pru*_*ati 6 flutter flutter-test flutter-dependencies flutter-channel flutter-plugin

我们已经在 TDD 方法中启动了一个关于 Flutter 的新项目。我正在使用状态管理提供程序。在尝试编写小部件测试时,我们面临着测试提供程序的问题。你能否用一个例子来建议为提供者和小部件注入提供者的单元测试。

我遇到以下问题

??? EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ?????????????????????????????????????
The following ProviderNotFoundException was thrown running a test:
Error: Could not find the correct Provider above this SplashScreen Widget

To fix, please:

Ensure the Provider is an ancestor to this SplashScreen Widget
Provide types to Provider
Provide types to Consumer
Provide types to Provider.of()
Always use package imports. Ex: `import 'package:my_app/my_code.dart';
Ensure the correct context is being used.
Run Code Online (Sandbox Code Playgroud)

???启动画面代码??????????????????????????????????????????

??? EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ?????????????????????????????????????
The following ProviderNotFoundException was thrown running a test:
Error: Could not find the correct Provider above this SplashScreen Widget

To fix, please:

Ensure the Provider is an ancestor to this SplashScreen Widget
Provide types to Provider
Provide types to Consumer
Provide types to Provider.of()
Always use package imports. Ex: `import 'package:my_app/my_code.dart';
Ensure the correct context is being used.
Run Code Online (Sandbox Code Playgroud)

预先感谢

Rém*_*let 7

您需要将要测试的小部件包装在该小部件使用的提供程序中。

因此,您可能需要编写:

await tester.pumpWidget(
  Provider<TokenProvider>(
    child: SplashScreen(),
  ),
);
Run Code Online (Sandbox Code Playgroud)


STE*_*EEL 5

如果您对此类代码进行了重复测试,则可以利用 extension

import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
import 'package:mockito/mockito.dart';

  Widget wrapWithMaterial() => MaterialApp(
    home: Provider<TokenProvider>(
      create: (_) => MockTokenProvider(),
      child: Scaffold(
        body: this,
      ),
    ),
  );

 class MockTokenProvider extends Mock implements TokenProvider {}
Run Code Online (Sandbox Code Playgroud)

现在在你的测试中你可以做

await tester.pumpWidget(
  SplashScreen().wrapWithMaterial()
);
Run Code Online (Sandbox Code Playgroud)