单元测试¶
纯 Rust¶
编写仅涉及 Rust 业务逻辑的测试相对简单:
Rust¶
#[tokio::test]
async fn my_async_test() {
let result = async_function().await;
assert_eq!(result, 42);
}
async fn async_function() -> i32 {
42
}
CLI¶
cargo test
Dart 与 Rust¶
编写在 Dart 和 Rust 之间传递信号的测试需要额外几行代码。首先,你需要构建 hub crate,使其位于 target 目录中,然后加载动态库。
Writing tests that pass signals between Dart and Rust requires a few extra lines of code. First, you need to build the hub crate so that it is located in the target directory, and then load the dynamic library.
test/custom_test.dart¶
import 'dart:io';
import 'package:test/test.dart';
import 'package:rinf/rinf.dart';
import 'package:my_app/src/bindings/bindings.dart';
void main() async {
// 构建动态库并加载它。
await Process.run('cargo', ['build'], runInShell: true);
await initializeRust(assignRustSignal, compiledLibPath: getLibPath());
// 在此编写测试逻辑。
expect(42, 42);
// ...
}
/// 获取动态库文件的预期路径。
/// 该路径应反映项目的文件夹结构。
String getLibPath() {
if (Platform.isMacOS) {
return 'target/debug/libhub.dylib';
} else if (Platform.isLinux) {
return 'target/debug/libhub.so';
} else if (Platform.isWindows) {
return 'target/debug/hub.dll';
} else {
throw UnsupportedError('This operating system is not for tests');
}
}
CLI¶
flutter test