#mocking #generator #mock #test

macro moq_derive

Mock generator (macro implementations)

4 releases (2 breaking)

0.3.1 Apr 15, 2022
0.3.0 Apr 15, 2022
0.2.0 Apr 11, 2022
0.1.0 Apr 7, 2022

#63 in #mock

Download history 122/week @ 2023-11-20 89/week @ 2023-11-27 139/week @ 2023-12-04 43/week @ 2023-12-11 31/week @ 2023-12-18 2/week @ 2023-12-25 6/week @ 2024-01-08 30/week @ 2024-01-15 43/week @ 2024-01-29 22/week @ 2024-02-05 31/week @ 2024-02-12 8/week @ 2024-02-19 52/week @ 2024-02-26 76/week @ 2024-03-04

167 downloads per month
Used in moq

MIT/Apache

60KB
1.5K SLoC

Moq

crates.io docs.rs build

This library provides macro that provides mock struct generating that implements trait.

[dependencies]
moq = "0.3"

Usage example

#[moq::automock]
trait Trait {
    fn func(&self, arg: i64) -> String;
}

#[test]
fn test_ok() {
    let mock = TraitMock::new()
        .expect_func(|arg: i64| {
            assert_eq!(arg, 42);
            format!("Hello, {}", arg)
        })
        .expect_func(|arg: i64| {
            assert_eq!(arg, -1);
            format!("Hello again, {}", -1)
        });
    
    mock.func(42);
    mock.func(-1);
}

#[test]
fn test_failed_extra_call() {
    let mock = TraitMock::new()
        .expect_func(|arg: i64| {
            assert_eq!(arg, 42);
            format!("Hello, {}", arg)
        });

    mock.func(42);
    mock.func(-1); // Panic here
}

#[test]
fn test_failed_missing_call() {
    let mock = TraitMock::new()
        .expect_func(|arg: i64| {
            assert_eq!(arg, 42);
            format!("Hello, {}", arg)
        })
        .expect_func(|arg: i64| {
            assert_eq!(arg, -1);
            format!("Hello again, {}", -1)
        });

    mock.func(42);
    // Panic here
}

async_trait also works, but the main limitation is to specify the automock macro above the async_trait

#[moq::automock]
#[async_trait::async_trait]
trait Trait {
    async fn func(&self, arg: i64) -> String;
}

#[tokio::test]
async fn test_ok() {
    let mock = TraitMock::new()
        .expect_func(|arg: i64| async {
            assert_eq!(arg, 42);
            format!("Hello, {}", arg)
        });
    
    mock.func(42).await;
}

You can find more examples in the tests.

TODO

  • Supporting generic functions
  • Supporting static functions
  • Macro moq::mock!(..) for generating mock struct for external trait
  • Generating mock struct for struct without trait
  • Capturing environment in moq::lambda!

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~2MB
~41K SLoC