#[automock\]属性中的元项目来达成:#[automock(type Key=u16; type Value=i32;)]
pub trait A {
type Key;
type Value;
fn foo(&self, k: Self::Key) -> Self::Value;
}
let mut mock = MockA::new();
mock.expect_foo()
.returning(|x: u16| i32::from(x));
assert_eq!(4, mock.foo(4));
mock!宏。但在创建之后,模拟对象的使用方法无异。pub trait A {
fn foo(&self);
}
pub trait B: A {
fn bar(&self);
}
mock! {
// 需要模拟的结构型
C {}
// C 中需要实现的第一个特征
trait A {
fn foo(&self);
}
// C中需要实现的第二个特征
trait B: A {
fn bar(&self);
}
}
let mut mock = MockC::new();
mock.expect_foo().returning(|| ());
mock.expect_bar().returning(|| ());
mock.foo();
mock.bar();
mock! 宏,而不是#[automock\]。你可以这样去模拟一个外部特征:mock! {
MyStruct {} // 模拟结构型的名称, 不需要 "Mock" 前缀
trait Clone { // 需要模拟的特征的定义
fn clone(&self) -> Self;
}
}
let mut mock1 = MockMyStruct::new();
let mock2 = MockMyStruct::new();
mock1.expect_clone()
.return_once(move || mock2);
let cloned = mock1.clone();
#[automock]
pub trait A {
fn foo() -> u32;
}
let ctx = MockA::foo_context();
ctx.expect().returning(|| 99);
assert_eq!(99, MockA::foo());
struct Foo{}
#[automock]
impl Foo {
fn from_i32(x: i32) -> Self {
// ...
}
fn foo(&self) -> i32 {
// ...
}
}
let ctx = MockFoo::from_i32_context();
ctx.expect()
.returning(|x| {
let mut mock = MockFoo::default();
mock.expect_foo()
.return_const(x);
mock
});
let foo = MockFoo::from_i32(42);
assert_eq!(42, foo.foo());
#[automock]
trait Foo<T: 'static> {
fn new(t: T) -> MockFoo<T>;
}
let ctx = MockFoo::<u32>::new_context();
ctx.expect()
.returning(|_| MockFoo::default());
let mock = MockFoo::<u32>::new(42u32);
checkpoint 方法。#[automock]
pub trait A {
fn foo() -> u32;
}
let ctx = MockA::foo_context();
ctx.expect()
.times(1)
.returning(|| 99);
ctx.checkpoint(); // Panics!
#[automock]
pub trait A {
fn build() -> Self;
fn bar(&self) -> i32;
}
let ctx = MockA::build_context();
ctx.expect()
.times(2)
.returning(|| MockA::default());
let mut mock0 = MockA::build();
mock0.expect_bar().return_const(4);
mock0.bar();
mock0.checkpoint(); // 不会对build方法进行checkpoint
let mock1 = MockA::build();
new方法。但是在模拟一个已经包含名为new的方法的结构型时,Mockall则不会自动创建。#[automock\]属性中提供一些额外的信息模拟外部方程才可正常使用。mod ffi {
use mockall::automock;
#[automock(mod mock;)]
extern "C" {
pub fn foo(x: u32) -> i64;
}
}
cfg_if! {
if #[cfg(test)] {
use self::ffi::mock::foo;
} else {
use self::ffi::foo;
}
}
fn do_stuff() -> i64 {
unsafe{ foo(42) }
}
#[cfg(test)]
mod t {
use super::*;
#[test]
fn test_foo() {
let ctx = ffi::mock::foo_context();
ctx.expect()
.returning(|x| i64::from(x + 1));
assert_eq!(43, do_stuff());
}
}
feature(proc_macro_hygiene)。使用方法与模拟外部功能一样,但是模拟模块的命名是自动生成的。#![feature(proc_macro_hygiene)]
mod outer {
use mockall::automock;
#[automock()]
pub(super) mod inner {
pub fn bar(x: u32) -> i64 {
// ...
}
}
}
cfg_if! {
if #[cfg(test)] {
use outer::mock_inner as inner;
} else {
use outer::inner;
}
}
#[cfg(test)]
mod t {
use super::*;
#[test]
fn test_foo_bar() {
let ctx = inner::bar_context();
ctx.expect()
.returning(|x| i64::from(x + 1));
assert_eq!(5, inner::bar(4));
}
}
原文作者:Rust语言中文社区;如有侵权,请联系管理员删除。