Flutter 颤振中的测试/模拟文件IO
我有一个简单的测试:Flutter 颤振中的测试/模拟文件IO,flutter,flutter-test,Flutter,Flutter Test,我有一个简单的测试: import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; Future<void> main() async { testWidgets( 'Simple empty test', (WidgetTester tester) async { print("1");
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> main() async {
testWidgets(
'Simple empty test',
(WidgetTester tester) async {
print("1");
await Directory('/tmp').exists();
print("2");
await tester.pumpWidget(Container());
},
);
}
导入'dart:io';
进口“包装:颤振/材料.省道”;
进口“包装:颤振试验/颤振试验.dart”;
Future main()异步{
测试小部件(
“简单空测试”,
(WidgetTester测试仪)异步{
印刷品(“1”);
等待目录('/tmp')。存在();
印刷品(“2”);
等待tester.pumpWidget(Container());
},
);
}
打印1
后它会冻结。我知道flatter在假异步区域中运行测试,并且我知道我需要用runAsync运行带有真实IO的代码
但是,是否也可以在不使用runAsync的情况下注入模拟IO文件系统并运行测试?在做了一些研究之后,我发现了google团队提供的软件包,它允许开发人员使用
本地文件系统
(基本上是dart:IO
),内存文件系统
或自定义的文件系统
尤其是MemoryFileSystem
甚至自定义的文件系统
对于单元和小部件测试来说都很方便,因为它们可以使用,所以不会在硬盘上创建任何文件。因此,在测试运行后创建和清理文件系统
要容易得多
这种方法的缺点是必须将文件系统
注入需要访问文件、目录等的每个模块
示例
import 'package:file/file.dart';
class DirectoryOperator {
final FileSystem fileSystem;
// Inject implementation of the FileSystem
DirectoryOperator({required this.fileSystem});
Future<void> methodOperatingOnFileSystem(String path) async {
Directory directory = fileSystem.directory(path);
await directory.create(recursive: true);
}
}
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_test/flutter_test.dart';
main() {
test('$DirectoryOperator creates directory on path', () async {
FileSystem fileSystem = MemoryFileSystem();
var systemUnderTest = DirectoryOperator(fileSystem: fileSystem);
String testPath = 'Path/to/dir';
await systemUnderTest.methodOperatingOnFileSystem(testPath);
bool doesDirectoryExist = await fileSystem.directory(testPath).exists();
expect(
doesDirectoryExist,
isTrue,
);
});
}