Simulacrum
A minimal library for creating mock objects by hand using stable Rust.
To install, add this line to your Cargo.toml:
[]
= "0.3.0"
Note that this crate has not yet reached version 1.0, so the API may change drastically between releases.
Using Mock Objects
Simulacrum mock objects provide a consistent interface that features call counts, parameter matching, return values, and modifying parameters by mutable reference.
// Create a mock object
let mut mock = new;
// Set up expectations for it
mock.expect_foo
.called_once;
mock.then
.expect_goop
.called_once
.with
.returning;
// Execute test code
m.foo;
assert_eq!;
// When the mock object is dropped, its expectations will be evaluated
See macros_high.rs
for a full run-through of the mock object user API.
Creating Mock Objects
Simulacrum provides several APIs at different levels of abstraction, so you can create mock objects with the level of control you desire. All mock objects created with Simulacrum expose the same user API, no matter which API level is used to create them.
The following examples all show how to mock this trait:
Note that the macro API only supports creating mocks from a trait, while the manual API allows you to create mock objects to stand in for structs as well.
High-Level Macro Example
The create_mock!
macro creates a mock object from a trait. Just copy over the trait's interface and annotate it:
extern crate simulacrum;
use *;
create_mock!
See macros_high.rs
for more examples of how to mock out different types of methods with create_mock!
.
Mid-Level Macros Example
If you need more control than the high-level macro offers, you can use the create_mock_struct!
and was_called!
macros. This is useful if you'd like to create mock objects with features that the high-level macro doesn't support, like generic methods. Note that you can mix-and-match these macros with the manual interface as well.
extern crate simulacrum;
use *;
create_mock_struct!
See macros_mid.rs
for more examples of how to mock out different types of methods with the Mid-Level Macros.
Manual Example
Create your mock objects manually for ultimate control. With this API, you can even create mocks to stand in for structs instead of traits. For a detailed example of the API, see the manual.rs
example.
extern crate simulacrum;
use *;