moq_derive

Crates.iomoq_derive
lib.rsmoq_derive
version0.3.1
sourcesrc
created_at2022-04-07 22:28:35.837443
updated_at2022-04-15 16:26:42.927489
descriptionMock generator (macro implementations)
homepage
repositoryhttps://github.com/LazyMechanic/moq
max_upload_size
id563939
size59,359
Artem (LazyMechanic)

documentation

https://docs.rs/moq

README

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.
Commit count: 17

cargo fmt