Can you help me understand Moq Callback?

前端 未结 5 861
傲寒
傲寒 2020-12-09 00:24

Using Moq and looked at Callback but I have not been able to find a simple example to understand how to use it.

Do you have a small working snippet whic

5条回答
  •  囚心锁ツ
    2020-12-09 01:06

    There are two types of Callback in Moq. One happens before the call returns; the other happens after the call returns.

    var message = "";
    mock.Setup(foo => foo.Execute(arg1: "ping", arg2: "pong"))
        .Callback((x, y) =>
        {
            message = "Rally on!";
            Console.WriteLine($"args before returns {x} {y}");
        })
        .Returns(message) // Rally on!
        .Callback((x, y) =>
        {
            message = "Rally over!";
            Console.WriteLine("arg after returns {x} {y}");
        });
    

    In both callbacks, we can:

    1. inspect method arguments
    2. capture method arguments
    3. change contextual state

提交回复
热议问题