trying to insp开发者_如何转开发ect and argument and need to retrieve it. what is the equivalent in Moq? or a way to do it in Moq?
figured it out, utilizing the callback functionality on the Mock Setup
int captured_int;
mocked_obj.Setup(x => x.SomeMethod(It.IsAny<int>()))
.Callback<int>(x => captured_int = x);
if your method has multiple params
int captured_int;
object captured_object;
mocked_obj.Setup(x => x.SomeMethod(It.IsAny<int>(), It.IsAny<object>()))
.Callback<int, object>((i, o) => {
captured_int = i;
captured_object = o;
});
then you can do asserts on the captured values;
Since Moq 4.9.0 you can access the list of invocations of the mocked object and do the asserts on those without the need for a callback:
[Test]
public void TestMoq()
{
var someClass = new Mock<ISomeClass>();
someClass.Object.SomeMethod(42, null);
someClass.Object.SomeMethod(88, "Hello");
// First invocation
Assert.AreEqual(42, (int) someClass.Invocations[0].Arguments[0]);
Assert.IsNull(someClass.Invocations[0].Arguments[1]);
// Second invocation
Assert.AreEqual(88, (int) someClass.Invocations[1].Arguments[0]);
Assert.AreEqual("Hello", someClass.Invocations[1].Arguments[1]);
}
Of course this is just an example, in real world code you have to be more careful with this method, mostly because all the arguments are accessible as object
s, instead of typed arguments as in the Callback
. Also the invocations are not tied to a Setup
, it's a list of all the invocations on the mocked class.
精彩评论