Skip to content

Instantly share code, notes, and snippets.

Created November 22, 2022 20:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
[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));
mod tests {
use super::*;
struct TestLogger(Vec<String>);
impl Logger for TestLogger {
fn log(&mut self, value: String) {
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