Can you help me understand Moq Callback?

前端 未结 5 884
傲寒
傲寒 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:16

    Callback is simply a means to execute any custom code you want when a call is made to one of the mock's methods. Here's a simple example:

    public interface IFoo
    {
        int Bar(bool b);
    }
    
    var mock = new Mock();
    
    mock.Setup(mc => mc.Bar(It.IsAny()))
        .Callback(b => Console.WriteLine("Bar called with: " + b))
        .Returns(42);
    
    var ret = mock.Object.Bar(true);
    Console.WriteLine("Result: " + ret);
    
    // output:
    // Bar called with: True
    // Result: 42
    

    I recently ran into an interesting use case for it. Suppose you expect some calls to your mock, but they happen concurrently. So you have no way of knowing the order in which they'd get called, but you want to know the calls you expected did take place (irrespective of order). You can do something like this:

    var cq = new ConcurrentQueue();
    mock.Setup(f => f.Bar(It.IsAny())).Callback(cq.Enqueue);
    Parallel.Invoke(() => mock.Object.Bar(true), () => mock.Object.Bar(false));
    Console.WriteLine("Invocations: " + String.Join(", ", cq));
    
    // output:
    // Invocations: True, False
    

    BTW don't get confused by the misleading "before Returns" and "after Returns" distinction. It is merely a technical distinction of whether your custom code will run after Returns has been evaluated or before. In the eyes of the caller, both will run before the value is returned. Indeed, if the method is void-returning you can't even call Returns and yet it works the same. For more information see https://stackoverflow.com/a/28727099/67824.

提交回复
热议问题