Skip to content

Instantly share code, notes, and snippets.

@squarism
Created May 28, 2023 20:30
Show Gist options
  • Save squarism/1d38dda87755bf3f4587b75149138299 to your computer and use it in GitHub Desktop.
Save squarism/1d38dda87755bf3f4587b75149138299 to your computer and use it in GitHub Desktop.
Mocking in Rust with a working mockall example
#[cfg(test)]
use mockall::{automock, predicate::*};
pub struct Visa {}
#[cfg_attr(test, automock)]
pub trait Chargable {
fn charge_credit_card(&self) -> u32;
}
impl Chargable for Visa {
fn charge_credit_card(&self) -> u32 {
println!("I really actually charged. You should never see this in dev.");
println!("This is like a network request going out or something.");
42
}
}
fn charge(adapter: &dyn Chargable) -> u32 {
adapter.charge_credit_card()
}
fn main() {
let visa = Visa {};
let amount = charge(&visa);
println!("Amount charged: {}", amount);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_test() {
let mut mock = MockChargable::new();
mock.expect_charge_credit_card().times(1).returning(|| 42);
let amount = charge(&mock);
assert_eq!(amount, 42);
}
}
// $ cargo run
// I really actually charged. You should never see this in dev.
// This is like a network request going out or something.
// Amount charged: 42
// $ cargo test
// running 1 test
// test tests::a_test ... ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment