Uses old Rust 2015

0.1.0 Apr 3, 2016

#142 in #unsafe

MIT/Apache

13KB
172 lines

Gratuitously unsafe mocks for Rust

Build Status Latest Version

This crate provides a macro for creating mock instances of trait objects in test code.

Installation

The crate is available on crates.io with a Cargo.toml like:

[dev-dependencies]
mock = "^0.1"

Release notes are available under GitHub releases.

As this crate provides a macro, it must be imported with the #[macro_use] attribute:

#[macro_use]
extern crate mock;

Creating Mocks

Mocks can be created with the mock!() macro. Simply provide the name of a trait to mock.

let m = mock!(BestTrait);

Traits may include generics.

let m = mock!(AsRef<String>);

The returned mock is immediately ready to use. Since none of the methods are mocked yet, any method call will execute std::unreachable!().

fn use_trait(best: &BestTrait) {
    // panics if `use_trait` invokes any methods that have not been mocked
}
use_trait(m);

Individual methods can be mocked by providing a function body. Suppose BestTrait has a method with the signature fn compute(&self, usize, Vec<i32>) -> String.

mock!(m.compute(usize, Vec<i32>) -> String { "success".to_string() });

assert_eq!("success".to_string(), m.compute(3, vec![1, 4, 1, 5]));

Any number of the trait methods may be mocked. Any methods that are not mocked will execute std::unreachable!().

A full working example looks like this:

#[macro_use]
extern crate mock;

trait BestTrait {
    fn compute(&self, usize, Vec<i32>) -> String;
    fn other(&self, String) -> Result<bool, ()>;
}

#[test]
fn your_test() {
    let m = mock!(BestTrait);
    mock!(m.compute(usize, Vec<i32>) -> String { "success".to_string() });
    // leave other() unimplemented

    use_trait(m);
}

fn use_trait(best: &BestTrait) {
    assert_eq!("success".to_string(), best.compute(3, vec![1, 4, 1, 5]));
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps