在Dart中模拟被测类的方法



我有一个辅助类(在Dart中),如下所示:

class AppInfoHelper {
Future<String> getAppName() async {
return getPackageInfo().then((info) => info.appName);
}
Future<String> getAppVersion() async {
return getPackageInfo().then((info) => info.version);
}
Future<String> getBuildNumber() async {
return getPackageInfo().then((info) => info.buildNumber);
}
Future<PackageInfo> getPackageInfo() async => PackageInfo.fromPlatform();

}

这个类的职责是提供应用信息。我使用PackageInfo作为库之一。由于某些原因,我不会提供PackageInfo作为构造函数参数。

如何为这个类编写适当的单元测试?我不确定如何做存根,因为我们getPackageInfo()方法是来自类在测试本身。

注意:我正在使用mockito (https://pub.dev/packages/mockito)和一些提到做spy之类的事情的参考资料,但我不认为它可以从Dart/Flutter mockito获得。

首先,如果你不为你的类提供PackageInfo的实例,那么你将不得不创建你自己的MockAppInfoHelper,这将让你使用一个假的PackageInfo类。

下面是一个实现的例子:

class MockAppInfoHelper extends AppInfoHelper {
MockAppInfoHelper(this._packageInfo);
final PackageInfo _packageInfo;
@override
Future<PackageInfo> getPackageInfo() async => _packageInfo;
}

要模拟一个假的PackageInfo类,您必须通过添加GenerateMocks注释并运行build_runner:

来生成一些模拟。
@GenerateMocks([PackageInfo])
import 'app_info_helper_test.mocks.dart'; // note that the name might change if your base file is not named app_info_helper_test
现在您可以开始编写测试方法,下面是getAppName的测试示例:
void main() {
group('AppInfoHelper', () {
late MockPackageInfo mockPackageInfo;
late MockAppInfoHelper mockAppInfoHelper;
/// setUp is called before each test, it'll ensure that the mock is reset.
setUp(() {
mockPackageInfo = MockPackageInfo();
mockAppInfoHelper = MockAppInfoHelper(mockPackageInfo);
});
test('test getAppName', () async {
const testAppName = 'testAppName';
// First arrange the mock to return the expected value.
when(mockPackageInfo.appName).thenReturn(testAppName);
// Then call the method you want to test.
final result = await mockAppInfoHelper.getAppName();
// Finally verify that the mock was called as expected.
verify(mockPackageInfo.appName);
expect(result, testAppName);
});
});
}

最新更新