#virtual #io #print #stdout #replace #println #vio

virtual-io

Mock stdin/out/err for testing

1 unstable release

0.1.0 Jul 1, 2023

#2379 in Rust patterns

Download history 52/week @ 2024-01-01 53/week @ 2024-01-08 52/week @ 2024-01-15 52/week @ 2024-01-22 54/week @ 2024-01-29 53/week @ 2024-02-05 71/week @ 2024-02-12 73/week @ 2024-02-19 91/week @ 2024-02-26 73/week @ 2024-03-04 78/week @ 2024-03-11 71/week @ 2024-03-18 67/week @ 2024-03-25 95/week @ 2024-04-01 67/week @ 2024-04-08 162/week @ 2024-04-15

401 downloads per month

MIT license

17KB
349 lines

Virtual IO

Virtual IO is a rust library for easily implementing stdin and stdout in a testable way. It replaces all println! and print! macro calls.

use virtual_io::{VirtualIo, Vio};

fn get_name() -> String {
    get_name_base(&mut virtual_io::new())
}

fn get_name_base(vio: &mut impl VirtualIo) -> String {
    vio.print("What is your name? ");
    let name = vio.read_line();
    vio.println(format!("Hello, {}!", name));
    name
}

#[cfg(test)]
mod test {
    use super::*;
    use virtual_io::VioFakeBuilder;

    #[test]
    fn test_get_name() {
        // Create a fake version of vio that we can inject into the base
        // function.
        let mut vio = VioFakeBuilder::new()
            // Add the expected io calls.
            .expect_stdout("What is your name? ")
            .provide_stdin("John")
            .expect_stdout("Hello, John!\n")
            // Build the fake vio.
            .build();
        // Assert that the return value is correct.
        assert_eq!(get_name_base(&mut vio), "John");
        // Assert that all io operations were identical to what was expected.
        assert_eq!(vio.get_actual(), vio.get_expected());
    }
}

No runtime deps