5

How does one setup a generic method using moq library in C#? Such as

Interface IA
{
    void foo();
    void Get<T>();
}

[Fact]
public void SetupGenericMethod()
{
    var mock = new Mock<IA>();
    mock.Setup(x=> x.Get<It.IsAny<???>()>()
}
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
sapphire
  • 61
  • 2
  • 3
  • 1
    Possible duplicate of [Mocking generic methods in Moq without specifying T](http://stackoverflow.com/questions/20072429/mocking-generic-methods-in-moq-without-specifying-t) – Old Fox Apr 30 '16 at 15:41

2 Answers2

4

If you don't need to do something that related to the type T, It can be done since Moq 4.13 (2019-09-01) by using It.IsAnyType for generic type arguments:

mock.Setup(x => x.Get<It.IsAnyType>())

Full Example:

public interface IA
{
    void Get<T>();
}


[Fact]
public void test()
{
    // Arrange
    bool didCallBackCalled = false;
    var mock = new Mock<IA>();
    mock.Setup(x => x.Get<It.IsAnyType>()).Callback(() => didCallBackCalled = true);

    // Act
    mock.Object.Get<string>();

    // Assert
    Assert.IsTrue(didCallBackCalled);
}
itaiy
  • 1,152
  • 1
  • 13
  • 22
0

When testing you should know what T should be for the test. Use the type for the setup. Also based on the naming in your example Get<T> should be returning something.

Interface IA
{
    void foo();
    T Get<T>();
}

[Fact]
public void SetupGenericMethod()
{
    var mockT = new Mock<FakeType>(); 
    var mock = new Mock<IA>();
    mock.Setup(x=> x.Get<FakeType>()).Returns(mockT.Object);
}

If you are actually looking for Mocking generic method call for any given type parameter. Then the answer to that question was to forego creating a mock and instead use a Stub, or mocking the interface yourself instead of using a mocking framework.

Community
  • 1
  • 1
Nkosi
  • 235,767
  • 35
  • 427
  • 472