Unit Testing¶
Pure Rust¶
Writing tests that only involve the business logic of Rust is relatively simple:
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 and Rust¶
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:convert';
import 'dart:io';
import 'package:test/test.dart';
import 'package:rinf/rinf.dart';
import 'package:my_app/src/bindings/bindings.dart';
void main() async {
// Build the dynamic library and load it.
await Process.run('cargo', ['build'], runInShell: true);
await initializeRust(assignRustSignal, compiledLibPath: getLibPath());
// Your test logic goes here.
expect(42, 42);
// ...
}
/// Gets the path of the dynamic library file.
/// Cargo is asked for its target directory,
/// which can be changed by `CARGO_TARGET_DIR` or Cargo config files.
String getLibPath() {
const args = ['metadata', '--format-version', '1', '--no-deps'];
final metadata = Process.runSync('cargo', args, runInShell: true);
final targetDir =
jsonDecode(metadata.stdout as String)['target_directory'] as String;
if (Platform.isMacOS) {
return '$targetDir/debug/libhub.dylib';
} else if (Platform.isLinux) {
return '$targetDir/debug/libhub.so';
} else if (Platform.isWindows) {
return '$targetDir/debug/hub.dll';
} else {
throw UnsupportedError('This operating system is not for tests');
}
}
CLI¶
flutter test