3 个版本
使用旧的 Rust 2015
0.2.3 | 2017 年 8 月 31 日 |
---|---|
0.2.2 | 2017 年 2 月 1 日 |
0.2.0 | 2017 年 1 月 29 日 |
排名 431 / 测试
14KB
209 行
MockMe
MockMe 是一个在 Rust 中运行单元(lib)测试时模拟依赖项/函数调用的工具。
注意
遗憾的是,由于 rust/cargo 执行测试的非确定性顺序,模拟的函数只能由单个测试注入。如果多个测试进行模拟,可能会因为竞争条件而随机崩溃。因此,这主要只是一个实验性的玩具 crate,不应在生产代码库中使用。
如何使用
目前,仅在 nightly 版本中工作。
只需像下面示例中那样使用宏。当此代码正常运行时,MockMe 将没有效果。但是,当代码作为单元测试的一部分运行时 #[cfg(test)]
,将使用模拟的标记。
#![feature(proc_macro)]
extern crate mockme;
use mockme::{mock, inject};
// Below we will create two mocking identifiers called id_1 and id_2.
// We will then provide the name of the two functions we are mocking, as well as
// their type signature. In future iterations, hopefully the signature won't be needed.
#[mock(id_1="external_db_call: fn(u32) -> String", id_2="other_call: fn() -> String")]
fn my_super_cool_function() -> String {
let input = 42u32;
// external_db_call will be replaced with fake_mocked_call during testing
let db_result = external_db_call(input);
// other_call will also be replaced
let other_result = other_call();
format!("I have two results! {} and {}", db_result, other_result)
}
// Finally, when we run our tests, we simply need to provide the identifier we previously used,
// as well as the name of the replacement function
#[test]
#[inject(id_1="db_fake", id_2="other_fake")]
fn actual_test2() {
let result = my_super_cool_function();
assert_eq!(result, "I have two results! Faker! and This is indeed a disturbing universe.");
}
fn db_fake(_: u32) -> String { "Faker!".to_string() }
fn other_fake() -> String { "This is indeed a disturbing universe.".to_string() }
贡献
欢迎所有贡献!这个库还处于初级阶段,所以任何帮助都很有价值。代码贡献、功能请求和错误报告都受到欢迎。
限制
目前,该库无法推断正在模拟的函数的签名。因此,程序员需要提供它,这损害了库的用户友好性。
依赖项
~17KB