Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Writing a testable console program
Post
Writing a testable console program
I have a class Foo
that prints something to stdout and I want to be able to write tests for it.
So I created a trait to abstract println!
, and gave it a prod implementation and a test implementation.
The test implementation simply writes the strings to a vector, so that tests can make assertions on the contents of the vector.
The problem is that since the MockIO
modifies itself, I'm forced to write the method's signature as fn println(&mut self, s: &str)
instead of fn println(&self, s: &str)
. Which in turns forces me to sprinkle mut
s all over the code.
// main.rs
mod foo;
mod io;
fn main() {
let mut io_interface = io::StdIO{};
foo::Foo::print_hello(&mut io_interface);
}
// foo.rs
use crate::io::{self, IO};
pub struct Foo {
}
impl Foo {
pub fn print_hello<I>(io_interface: &mut I) where I: IO {
io_interface.println("Hello, World!");
}
}
#[cfg(test)]
#[test]
fn print_hello_world() {
let mut mock_io = io::MockIO::new();
Foo::print_hello(&mut mock_io);
assert_eq!(mock_io.outputs[0], "Hello, World!");
}
// io.rs
pub struct StdIO;
pub trait IO {
fn println(&mut self, s: &str);
}
impl IO for StdIO {
fn println(&mut self, s: &str) {
println!("{}", s);
}
}
#[cfg(test)]
pub struct MockIO {
pub outputs: Vec<String>,
}
#[cfg(test)]
impl IO for MockIO {
fn println(&mut self, s: &str) {
self.outputs.push(s.to_string());
}
}
#[cfg(test)]
impl MockIO {
pub fn new() -> Self {
MockIO { outputs:vec![] }
}
}
So my questions are:
- is there a way to write
MockIO
so that I don't have to change the signature ofIO::println()
for the sake of the test class? - is there a better way to solve this problem altogether?
Feel free to point out any non-idiomatic code as well. I've done a fair bit of software development but am new to Rust.
1 comment thread