Moq'ing a Func or Action

Just ran into trying to test a method that takes a callback in the form of Func. Initially i figured, it's a func, dead simple, i'll just roll my own func. But the method calls it multiple times with different input and expecting different output. At that point, I really didn't want to write a fake that that could check input on those invocations and return the right thing and let me track invocations. That's what Moq does so beautifully. Except it doesn't for Func or Action.

Fortunately the solution was pretty simple. All i needed was a class that implemented a method with the same signature as the Func, mock it and pass a reference to the mocked method in as my func, voila, mockable Func:

public class FetchStub {
  public virtual PageNodeData Fetch(Title title) { return null; }
}

[Test]
public Can_moq_func() {

  // Arrange
  var fetchMock = new Mock<FetchStub>();
  var title = ...;
  var node = ...;
  fetchMock.Setup( x => x.Fetch(It.Is(y => y == title))
    .Returns(node)
    .Verifiable();
  ...

  // Act
  var nodes = titleResolver.Resolve(titles, fetchMock.Object.Fetch);

  // Assert
  fetchMock.VerifyAll();
  ...
}

Now i can set up as many expectations for different input as i want and verify all invocations at the end.