This crate provides a macro for creating mock instances of trait objects in test code.
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
extern crate mock; ```
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
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
extern crate mock;
trait BestTrait {
fn compute(&self, usize, Vec fn yourtest() {
let m = mock!(BestTrait);
mock!(m.compute(usize, Vec } fn usetrait(best: &BestTrait) {
asserteq!("success".to_string(), best.compute(3, vec![1, 4, 1, 5]));
}
``` Licensed under either of at your option. 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.[test]
use_trait(m);
License
Contribution