pub struct FakeStore<WrappedClosure: Clone> {
_name: &'static str,
implementation: Option<WrappedClosure>,
}
impl<WrappedClosure: Clone> FakeStore<WrappedClosure> {
pub fn new(function_name: &'static str) -> Self {
Self {
_name: function_name,
implementation: None,
}
}
pub fn setup(&mut self, new_f: WrappedClosure) {
self.implementation = Some(new_f);
}
pub fn clear(&mut self) {
self.implementation = None;
}
pub fn is_set(&self) -> bool {
self.implementation.is_some()
}
pub fn get(&self) -> Option<WrappedClosure> {
self.implementation.clone()
}
}
#[cfg(test)]
mod tests {
use std::rc::Rc;
use super::*;
#[test]
fn new_store_has_no_implementation_set() {
let store: FakeStore<Rc<dyn Fn() -> i32>> = FakeStore::new("test_fn");
assert!(!store.is_set());
}
#[test]
fn setup_marks_implementation_as_set() {
let mut store: FakeStore<Rc<dyn Fn() -> i32>> = FakeStore::new("test_fn");
store.setup(Rc::new(|| 42));
assert!(store.is_set());
}
#[test]
fn get_returns_the_implementation_passed_to_setup() {
let mut store: FakeStore<Rc<dyn Fn(i32) -> i32>> = FakeStore::new("test_fn");
store.setup(Rc::new(|x: i32| x + 1));
let f = store.get();
assert!(f.is_some());
assert_eq!(f.unwrap()(41), 42);
}
#[test]
fn setup_overwrites_previous_implementation() {
let mut store: FakeStore<Rc<dyn Fn() -> i32>> = FakeStore::new("test_fn");
store.setup(Rc::new(|| 1));
store.setup(Rc::new(|| 2));
let f = store.get();
assert!(f.is_some());
assert_eq!(f.unwrap()(), 2);
}
#[test]
fn clear_removes_the_implementation() {
let mut store: FakeStore<Rc<dyn Fn() -> i32>> = FakeStore::new("test_fn");
store.setup(Rc::new(|| 42));
store.clear();
assert!(!store.is_set());
}
#[test]
fn get_returns_none_when_no_implementation_is_set() {
let store: FakeStore<Rc<dyn Fn() -> i32>> = FakeStore::new("test_fn");
assert!(store.get().is_none());
}
}