generic_method/
generic_method.rs

1use predicates::float::is_close;
2use ridicule::mock;
3use ridicule::predicate::function;
4
5trait Haha
6{
7    type Hello;
8}
9
10trait Foo
11{
12    fn bar<Baz: Haha>(&self, num: u128) -> Baz::Hello;
13
14    fn abc<ThingA, ThingB>(&mut self, thing_a: ThingA, thing_b: ThingB);
15}
16
17mock! {
18    MockFoo {}
19
20    impl Foo for MockFoo
21    {
22        fn bar<Baz: Haha>(&self, num: u128) -> Baz::Hello;
23
24        fn abc<ThingA, ThingB>(&mut self, thing_a: ThingA, thing_b: ThingB);
25    }
26}
27
28impl Haha for u16
29{
30    type Hello = String;
31}
32
33impl Haha for &str
34{
35    type Hello = u8;
36}
37
38fn main()
39{
40    let mut mock_foo = MockFoo::new();
41
42    unsafe {
43        mock_foo.expect_bar::<u16>().returning(|_me, num| {
44            println!("bar was called with {num}");
45
46            "Hello".to_string()
47        })
48    }
49    .times(3);
50
51    unsafe {
52        mock_foo.expect_bar::<&str>().returning(|_me, num| {
53            println!("bar was called with {num}");
54
55            128u8
56        });
57    }
58
59    unsafe {
60        mock_foo
61            .expect_abc::<&str, f64>()
62            .with(
63                function(|thing_a: &&str| thing_a.starts_with("Good morning")),
64                is_close(7.13081),
65            )
66            .returning(|_me, _thing_a, _thing_b| {
67                println!("abc was called");
68            })
69    }
70    .times(1);
71
72    assert_eq!(mock_foo.bar::<u16>(123), "Hello".to_string());
73    assert_eq!(mock_foo.bar::<u16>(123), "Hello".to_string());
74    assert_eq!(mock_foo.bar::<u16>(123), "Hello".to_string());
75
76    // Would panic
77    // mock_foo.bar::<String>(123);
78
79    assert_eq!(mock_foo.bar::<&str>(456), 128);
80
81    mock_foo.abc(
82        concat!(
83            "Good morning, and in case I don't see ya, good afternoon,",
84            " good evening, and good night!"
85        ),
86        7.13081f64,
87    );
88}