Crates.io | covers |
lib.rs | covers |
version | 0.1.0-beta.7 |
source | src |
created_at | 2020-06-01 13:00:30.720784 |
updated_at | 2020-06-02 17:20:42.037462 |
description | Lightweight library allowing to mock functions in Rust |
homepage | https://github.com/reanimatorzon/covers |
repository | https://github.com/reanimatorzon/covers |
max_upload_size | |
id | 248632 |
size | 12,457 |
Lightweight library allowing to mock functions in Rust
https://crates.io/crates/covers
use covers::{mocked, mock};
#[mocked(mock_foo)]
fn foo(name: &str) -> String {
format!("Response: Foo = {}", name)
}
fn mock_foo(another_name: &str) -> String {
format!("Response: Mocked(Foo = {})", another_name)
}
#[mocked(module::mock_bar)]
fn bar(name: &str) -> String {
format!("Response: Bar = {}", name)
}
pub struct Struct {}
mod module {
use super::*;
#[mock]
pub fn mock_bar(name: &str) -> String {
let original_function_result = _bar(name);
format!("Response: Mocked({})", original_function_result)
}
pub fn yyy(this: Struct, name: &str) -> String {
format!("Response: Mocked({})", name)
}
}
impl Struct {
#[mocked(Struct::mock_baz, scope = impl)]
fn baz(name: &str) -> String {
format!("Response: Baz = {}", name)
}
fn mock_baz(name: &str) -> String {
format!("Response: Baz = {}", name)
}
#[mocked(module::yyy)]
fn xxx(self, name: &str) -> String {
format!("Response: Baz = {}", name)
}
}
You can mock all types of functions with #[mocked(mock_fn)]
:
scope = impl
)this: Struct
or _self: Struct
as the first argument instead of self
)You can manually create and store mock functions:
#[cfg(test)] mod tests {}
)scope = impl
hint is required for static struct functions / static methods
There is no need in adding scope = impl
struct variant's function,
it is set automatically for all functions with the first argument self
#[mock]
let compiler know that this code should not be compiled for release builds.
Otherwise, it makes related function pub
. You can disable this logic passing no-pub
for the crate's features
Using #[mock]
is strictly required when we use reference to an original function
inside. (Usually it is the same name function prepended by underscore _
). Otherwise release build could fail.
You can change a prefix of original function passing features=["__"]
or features=["_orig_"]
in [dependencies]
block of Cargo.toml
for covers
crate. One underscore is default - "_"
_original_function()
in your tests
you should be aware of: cargo test --release
can lead to unexpected results
or assertion errors - cause no #[cfg(debug_assertions)]
enabled.
Consider a test be reworked, narrow scope or avoid using original functionsNB: You can find lots of usage examples here - in the crate of integration tests.