Gratuitously unsafe mocks for Rust ================================== [![Build Status](https://api.travis-ci.org/dtolnay/mock.svg?branch=master)](https://travis-ci.org/dtolnay/mock) [![Latest Version](https://img.shields.io/crates/v/mock.svg)](https://crates.io/crates/mock) This crate provides a macro for creating mock instances of trait objects in test code. ## Installation The crate is available on [crates.io](https://crates.io/crates/mock) with a `Cargo.toml` like: ```toml [dev-dependencies] mock = "^0.1" ``` Release notes are available under [GitHub releases](https://github.com/dtolnay/mock/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); ``` 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) -> String`. ```rust mock!(m.compute(usize, Vec) -> 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: ```rust #[macro_use] extern crate mock; trait BestTrait { fn compute(&self, usize, Vec) -> String; fn other(&self, String) -> Result; } #[test] fn your_test() { let m = mock!(BestTrait); mock!(m.compute(usize, Vec) -> 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 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 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.