考虑到以下使用mockall库的测试上下文,我怎样才能令人满意地返回对
cmd
的引用,这将允许我对随后的链接方法调用做出断言?
mock! {
Cmd {}
impl CustomCommand for Cmd {
fn args(&mut self, args: &[String]) -> &mut Self;
fn output(&mut self) -> std::io::Result<Output>;
fn spawn(&mut self) -> std::io::Result<std::process::Child>;
fn status(&mut self) -> std::io::Result<ExitStatus>;
}
}
#[test]
fn test_x() {
let mut cmd = MockCmd::new();
cmd.expect_args().times(1).returning(|_| &mut cmd);
// results in:
// expected `MockCmd`, found `&mut MockCmd`
cmd.expect_args().times(1).returning(|_| cmd);
// results in:
// move occurs because `cmd` has type `tests::MockCmd`, which does not implement the `Copy` trait
// NOTE: I don't think I _can_ implement Copy for my struct because it's a newtype on top of Command
cmd.expect_output()
.times(1)
.returning(|| Ok(create_output(0, vec![], vec![])));
// Call the methods in the desired order
let args = vec![String::from(":P")];
let _x = cmd.args(&args).output();
}
这是不可能的,请参阅问题#106。正如本期所建议的,您可以做的最接近的事情是返回第二个
MockCmd
并对其设定期望。不过,这确实意味着您期望调用方法的特定顺序。如果这对您来说还不够好,您可以在 mockall
的存储库中打开问题。
#[test]
fn test_x() {
let mut cmd = MockCmd::new();
cmd.expect_args().once().returning(|_| {
let mut cmd = MockCmd::new();
cmd.expect_output()
.once()
.returning(|| Ok(create_output(0, vec![], vec![])));
cmd
});
// Call the methods in the desired order
let args = vec![String::from(":P")];
let _x = cmd.args(&args).output();
}