Skip to content

Instantly share code, notes, and snippets.

@maxday
Created November 22, 2022 20:56
Show Gist options
  • Save maxday/ae3c9f219c35c228dadd5359def5a833 to your computer and use it in GitHub Desktop.
Save maxday/ae3c9f219c35c228dadd5359def5a833 to your computer and use it in GitHub Desktop.
[RUST] How to test println?
// ❌ not testable
fn greeting_hard_to_test(nb: i32, name: &str) {
for _ in 0..nb {
println!("hi {}", name);
}
}
// ✅ easy to test
trait Logger {
fn log(&mut self, value: String);
}
struct ConsoleLogger;
impl Logger for ConsoleLogger {
fn log(&mut self, value: String) {
println!("{}", value);
}
}
fn greeting(nb: i32, name: &str, logger: &mut dyn Logger) {
for _ in 0..nb {
logger.log(format!("hi {}", name));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct TestLogger(Vec<String>);
impl Logger for TestLogger {
fn log(&mut self, value: String) {
self.0.push(value);
}
}
#[test]
fn greeting_test() {
let mut test_logger = TestLogger::default();
greeting(2, "maxday", &mut test_logger);
assert_eq!(2, test_logger.0.len());
assert_eq!("hi maxday", test_logger.0[0]);
assert_eq!("hi maxday", test_logger.0[1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment