Skip to content

Commit

Permalink
Merge pull request #185 from asomers/slices
Browse files Browse the repository at this point in the history
Allow mocking methods that return slices
  • Loading branch information
asomers committed Aug 29, 2020
2 parents 0da29cd + ef65828 commit 895d6a2
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ This project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased] - ReleaseDate
### Added
- Methods returning slices can now be mocked. Their expectations take `Vec`s.
([#185](https://github.com/asomers/mockall/pull/185))

- Compatibility with the `#[async_trait]` macro.
([#183](https://github.com/asomers/mockall/pull/183))

Expand Down
1 change: 1 addition & 0 deletions mockall/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,7 @@
//! [`CStr`](std::ffi::CStr),
//! [`OsStr`](std::ffi::OsStr),
//! [`Path`](std::path::Path),
//! [`Slice`][std::slice],
//! and
//! [`str`](std::str)
//! types are supported. Using this feature is automatic:
Expand Down
9 changes: 9 additions & 0 deletions mockall/tests/automock_deref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ trait Foo {
fn desc(&self) -> &OsStr;
fn path(&self) -> &Path;
fn text(&self) -> &'static str;
fn slice(&self) -> &[i32];
}

mod return_const {
Expand Down Expand Up @@ -62,4 +63,12 @@ mod return_const {
mock.expect_text().return_const(TEXT);
assert_eq!("abcd", mock.text());
}

#[test]
fn slice() {
let r = vec![1, 2, 3];
let mut mock = MockFoo::new();
mock.expect_slice().return_const(r);
assert_eq!(&[1, 2, 3], mock.slice());
}
}
26 changes: 26 additions & 0 deletions mockall_derive/src/mock_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,32 @@ fn destrify(ty: &mut Type) {
*tr.elem = pathbuf_ty,
Type::Path(ref path) if *path == str_ty =>
*tr.elem = string_ty,
Type::Slice(ts) => {
let inner = (*ts.elem).clone();
let mut segments = Punctuated::new();
segments.push(format_ident!("std").into());
segments.push(format_ident!("vec").into());
let mut v: PathSegment = format_ident!("Vec").into();
let mut abga_args = Punctuated::new();
abga_args.push(GenericArgument::Type(inner));
v.arguments = PathArguments::AngleBracketed(
AngleBracketedGenericArguments {
colon2_token: None,
lt_token: Token![<](Span::call_site()),
args: abga_args,
gt_token: Token![>](Span::call_site()),
}
);
segments.push(v);

*tr.elem = Type::Path(TypePath {
qself: None,
path: Path {
leading_colon: Some(Token![::](Span::call_site())),
segments
}
});
},
_ => (), // Nothing to do
};
}
Expand Down

0 comments on commit 895d6a2

Please sign in to comment.