sapphire
sapphire

Reputation: 61

moq generic method setup on interface

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<???>()>()
}

Upvotes: 5

Views: 6811

Answers (2)

itaiy
itaiy

Reputation: 1304

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);
}

Upvotes: 4

Nkosi
Nkosi

Reputation: 247551

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.

Upvotes: 0

Related Questions