Search code examples
c#unit-testingjustmock

Mocking a generic protected method


public class BaseClass
{
     protected static bool GetSomething<T>(HttpWebRequest request, out T response)
     {

     }
}


public class Class
{
     public bool DoSomething(string arg1, string arg2, out string reason)
     { 

          if (GetSomething(request, out response))
          {

          }  

     }
}

I'm trying to test DoSomething, but in order to do that I need to mock GetSomething. I can't seem to be able to mock it unless I change the GetSomething method so that it isn't generic. If I do that, the following works:

var successfullResponse = new Response { Status = AuthenticationStatus.Success };
Mock.SetupStatic(typeof(Class));
Mock.NonPublic.Arrange<Class>("GetSomething", ArgExpr.IsAny<HttpWebRequest>(), ArgExpr.Out(successfullLoginResponse));

string reason;
var classInstance = new Class();
bool result = classInstance.DoSomething(arg1, arg2, out reason);
Assert.IsTrue(result);
Assert.IsNull(reason);

Shouldn't the same call work when GetSomething is generic? If not, how can I mock GetSomething?

*We've submitted a ticket to Telerik. I'll update this post as soon as I discover anything.


Solution

  • Generic methods can be arranged through the reflection API, like so:

    var getSomething = typeof(BaseClass)
           // get GetSomething<T> using reflection
           .GetMethod("GetSomething", BindingFlags.NonPublic | BindingFlags.Static) 
           // make it into GetSomething<Response>
           .MakeGenericMethod(typeof(Response)); 
    
    // and arrange
    Mock.NonPublic.Arrange<bool>(method,
            ArgExpr.IsAny<HttpWebRequest>(),
            ArgExpr.Out(successfullLoginResponse))
       .Returns(true);