Testing in Android

Building on Testing, we will now look at how unit tests work in AOSP. Use the rust_test module for your unit tests:

testing/Android.bp:

  1. rust_library {
  2. name: "libleftpad",
  3. crate_name: "leftpad",
  4. srcs: ["src/lib.rs"],
  5. }
  6. rust_test {
  7. name: "libleftpad_test",
  8. crate_name: "leftpad_test",
  9. srcs: ["src/lib.rs"],
  10. host_supported: true,
  11. test_suites: ["general-tests"],
  12. }

testing/src/lib.rs:

  1. #![allow(unused)]
  2. fn main() {
  3. //! Left-padding library.
  4. /// Left-pad `s` to `width`.
  5. pub fn leftpad(s: &str, width: usize) -> String {
  6.     format!("{s:>width$}")
  7. }
  8. #[cfg(test)]
  9. mod tests {
  10.     use super::*;
  11.     #[test]
  12.     fn short_string() {
  13.         assert_eq!(leftpad("foo", 5), "  foo");
  14.     }
  15.     #[test]
  16.     fn long_string() {
  17.         assert_eq!(leftpad("foobar", 6), "foobar");
  18.     }
  19. }
  20. }

You can now run the test with

  1. atest --host libleftpad_test

The output looks like this:

  1. INFO: Elapsed time: 2.666s, Critical Path: 2.40s
  2. INFO: 3 processes: 2 internal, 1 linux-sandbox.
  3. INFO: Build completed successfully, 3 total actions
  4. //comprehensive-rust-android/testing:libleftpad_test_host PASSED in 2.3s
  5. PASSED libleftpad_test.tests::long_string (0.0s)
  6. PASSED libleftpad_test.tests::short_string (0.0s)
  7. Test cases: finished with 2 passing and 0 failing out of 2 test cases

Notice how you only mention the root of the library crate. Tests are found recursively in nested modules.