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:

toml [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:

```rust

[macro_use]

extern crate mock; ```

Creating Mocks

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

rust let m = mock!(BestTrait);

Traits may include generics.

rust 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!().

rust 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.

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

asserteq!("success".tostring(), 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:

```rust

[macro_use]

extern crate mock;

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

[test]

fn yourtest() { let m = mock!(BestTrait); mock!(m.compute(usize, Vec) -> String { "success".tostring() }); // leave other() unimplemented

use_trait(m);

}

fn usetrait(best: &BestTrait) { asserteq!("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.