#mocking #generator #test

macro moq_derive

Mock generator (macro implementations)

5 releases (3 breaking)

0.4.0 Nov 5, 2024
0.3.1 Apr 15, 2022
0.3.0 Apr 15, 2022
0.2.0 Apr 11, 2022
0.1.0 Apr 7, 2022

#201 in #mocking

Download history 11/week @ 2024-08-08 9/week @ 2024-08-15 16/week @ 2024-08-22 22/week @ 2024-08-29 7/week @ 2024-09-05 48/week @ 2024-09-12 40/week @ 2024-09-19 44/week @ 2024-09-26 68/week @ 2024-10-03 26/week @ 2024-10-10 27/week @ 2024-10-17 63/week @ 2024-10-24 231/week @ 2024-10-31 118/week @ 2024-11-07 61/week @ 2024-11-14 19/week @ 2024-11-21

441 downloads per month
Used in moq

MIT/Apache

64KB
1.5K SLoC

Moq

Crates.io Version docs.rs GitHub Actions Workflow Status

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

[dependencies]
moq = "0.4"

Usage example

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

#[test]
fn test_ok() {
    let mock = MockTrait::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]
#[should_panic]
fn test_failed_extra_call() {
    let mock = MockTrait::new()
        .expect_func(|arg: i64| {
            assert_eq!(arg, 42);
            format!("Hello, {}", arg)
        });

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

#[test]
#[should_panic]
fn test_failed_missing_call() {
    let mock = MockTrait::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 = MockTrait::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

~0.7–1.1MB
~24K SLoC