Abhinav Galodha
Abhinav Galodha

Reputation: 9878

Mock a generic method with Constraint using Moq

I am trying to Mock a generic method in a class. I am new to Moq and am not able to figure out the right way of mocking the method.

My code which needs to be tested and mocked.

public class WebServicesManager
{
    public static void Function1<TClient>()
        where TClient : SoapHttpClientProtocol, new()
    {
       //code
    }
}

The generic method Function1 accepts the generic type, which inherits from SoapHttpClientProtocol, which is basically the proxy for legacy asmx web services.

For testing the above method, am trying to mock the generic type parameter TClient. But I need the right method to do this, I tried the following code, but I am unable to find the right code.

    [TestMethod]
    public void Function1Test()
    {
        var mockService = new Mock<SoapHttpClientProtocol>();
        WebServicesManager.Function1<????>();
    }

One of the approaches that I thought of was to use a FakeClass which inherits from SoapHttpClientProtocol and then to call the generic method using the Fake class.

Also, I have read other answers here, most of them suggest to use an interface, which is correct but in my case, since the proxy code is Auto generated (client-side proxy code), so I have the limitation that I can't use the Interface.

Is it possible that I can mock the class SoapHttpClientProtocol and pass it as a generic parameter?

Upvotes: 4

Views: 1724

Answers (1)

Steven Liekens
Steven Liekens

Reputation: 14088

One of the approaches that I thought of was to use a FakeClass which inherits from SoapHttpClientProtocol and then to call the generic method using the Fake class.

Is it possible that I can mock the class SoapHttpClientProtocol and pass it as a generic parameter?

Yes, if you wrap the mock in the FakeClass.

public class FakeClient : SoapHttpClientProtocol
{
    public static Mock<SoapHttpClientProtocol> Mock { get; set; }

    public override object GetData() => Mock.Object.GetData();

    public override object SendData(object data) => Mock.Object.SendData(data);
}

[TestMethod]
public void Function1Test()
{
    FakeClient.Mock = new Mock<SoapHttpClientProtocol>();
    FakeClient.Mock.Setup(mock => mock.GetData()).Returns(...));
    FakeClient.Mock.Setup(mock => mock.SendData(It.IsAny<object>())).Callback(...));

    WebServicesManager.Function1<FakeClient>();
}

Upvotes: 1

Related Questions