summaryrefslogtreecommitdiff
path: root/examples/generic_fn_method.rs
blob: 3330269c4f1bbf2ed31c651be7e96ebf29b1c9f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use std::path::PathBuf;

use ridicule::mock;

trait Foo
{
    fn do_something<Callback>(&self, cb: Callback)
    where
        Callback: Fn(u64) -> String;

    fn do_something_else<Callback, Value>(&self, cb: Callback)
    where
        Callback: Fn(f32) -> Value;
}

mock! {
    MockFoo {}

    impl Foo for MockFoo
    {
        fn do_something<Callback>(&self, cb: Callback)
        where
            Callback: Fn(u64) -> String;

        fn do_something_else<Callback, Value>(&self, cb: Callback)
        where
            Callback: Fn(f32) -> Value;
        }
}

fn main()
{
    let mut mock_foo = MockFoo::new();

    unsafe {
        mock_foo
            .expect_do_something()
            .returning(|_me, cb: fn(_) -> _| {
                println!("do_something was called");

                let cb_res = cb(42);

                println!("Received '{cb_res}' from callback");
            });
    }

    unsafe {
        mock_foo
            .expect_do_something_else()
            .returning(|_me, cb: fn(_) -> PathBuf| {
                println!("do_something_else was called");

                let cb_res = cb(255.255);

                println!("Received '{}' from callback", cb_res.display());
            });
    }

    mock_foo.do_something((|num| format!("Hello there {num}")) as fn(_) -> _);

    mock_foo.do_something_else((|_| PathBuf::from(r"a/b/c.txt")) as fn(_) -> _);
}