我正在寻找一种方法来捕获传递给方法的实际参数,以便稍后检查它。想法是获取传递的参数然后对它执行断言。
例如:
var foo = Mock<Foo>();
var service = Mock<IService>();
service.Expect(s => s.Create(foo));
service.Create(new Foo { Currency = "USD" });
Assert(foo.Object.Currency == "USD");
或者更复杂的例子:
Foo foo = new Foo { Title = "...", Description = "..." };
var bar = Mock.NewHook<Bar>();
var service = new Mock<IService>();
service.Expect(s => s.Create(bar));
new Controller(service.Object).Create(foo);
Assert(foo.Title == bar.Object.Title);
Assert(foo.Description == bar.Object.Description);
答案 0 :(得分:13)
我认为你正在寻找与Moq的回调相当的东西:
var foo = Mock<Foo>();
var service = Mock<IService>();
service.Setup(s => s.Create(foo.Object)).Callback((T foo) => Assert.AreEqual("USD", foo.Currency))
service.Object.Create(new Foo { Currency = "USD" });
答案 1 :(得分:0)
如果需要对传递给对象的参数进行断言,那么您的测试似乎正在处理错误的对象。而不是声明传递给方法的参数,而是为调用正确参数的调用类编写测试。
答案 2 :(得分:0)
另见&#34; Callbacks&#34;在Moq's Quickstart documentation中:
usort ($data, function ($a, $b)
{
$arrayorder = array("z", "q", "9", "1", "a", "u");
$ea = array_search(substr($a,0,1), $arrayorder );
$eb = array_search(substr($b,0,1), $arrayorder );
if ($ea == $eb) {
if ( $a == $b ) {
return 0;
}
else {
return ($a< $b) ? -1 : 1;
}
}
return ($ea< $eb) ? -1 : 1;
});