Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moq generic method setup on interface

Tags:

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<???>()>()
}
like image 366
sapphire Avatar asked Apr 29 '16 23:04

sapphire


1 Answers

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);
}
like image 120
itaiy Avatar answered Oct 11 '22 01:10

itaiy