Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Request: Sequential Returns #3

Open
crmckenzie opened this issue Sep 12, 2019 · 1 comment
Open

Feature Request: Sequential Returns #3

crmckenzie opened this issue Sep 12, 2019 · 1 comment

Comments

@crmckenzie
Copy link

struct MyMock {
    pub mock_do_stuff: Mock<(), i32>,
}

impl MyMock {
    pub fn do_stuff(&self) -> i32 {
        self.mock_do_stuff.call(())
    }
}

impl Default for MyMock {
    fn default() -> MyMock {
        MyMock {
            mock_do_stuff: Mock::new(10),
        }
    }
}

#[test]
pub fn playground() {
    let mock = MyMock::default();

    assert_eq!(mock.do_stuff(), 10);

    mock.mock_do_stuff.return_value(42);
    mock.mock_do_stuff.return_value(84);

    let result1 = mock.do_stuff();
    let result2 = mock.do_stuff();

    assert_eq!(result1, 42); // returns 84; desire is it would return 42 on the first call and 84 on any remaining calls.
    assert_eq!(result2, 84);
}
@smmoosavi
Copy link

You can use this struct:

usage:

    #[test]
    fn use_with_mock() {
        let expected = vec![1, 2, 3];
        let generic = Generic::new(expected);
        let mock = Mock::default();
        mock.use_closure(generic.clone().into());
        assert_eq!(mock.call(()), 1);
        assert_eq!(mock.call(()), 2);
        assert_eq!(mock.call(()), 3);
        assert!(generic.done());
    }

code:

use std::fmt::Debug;
use std::sync::{Arc, RwLock};

#[derive(Clone, Debug)]
pub struct Generic<T: Clone + Debug + PartialEq> {
    expected: Arc<RwLock<(usize, Vec<T>)>>,
}

impl<T: Clone + Debug + PartialEq> Generic<T> {
    pub fn new(expected: Vec<T>) -> Self {
        Generic {
            expected: Arc::new(RwLock::new((0, expected))),
        }
    }
    pub fn next(&self) -> Option<T> {
        let mut state = self.expected.write().unwrap();
        if state.0 >= state.1.len() {
            None
        } else {
            let res = state.1[state.0].clone();
            state.0 += 1;
            Some(res)
        }
    }
    pub fn done(&self) -> bool {
        let state = self.expected.read().unwrap();
        state.0 >= state.1.len()
    }
}

impl<T: 'static + Clone + Debug + PartialEq + Send + Sync, C> From<Generic<T>>
    for Box<dyn Fn(C) -> T + Send + Sync>
{
    fn from(generic: Generic<T>) -> Self {
        Box::new(move |_| generic.next().unwrap())
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants