模拟通用的受保护方法

时间:2015-03-20 15:57:08

标签: c# unit-testing justmock

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))
          {

          }  

     }
}

我试图测试DoSomething,但为了做到这一点,我需要模拟GetSomething。除非我更改GetSomething方法以使其不通用,否则我似乎无法模拟它。如果我这样做,以下工作:

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);
当GetSomething是通用的时,不应该使用相同的调用工作吗?如果没有,我怎么能模拟GetSomething?

*我们已经向Telerik提交了一张票。我发现任何内容后,我会立即更新这篇文章。

1 个答案:

答案 0 :(得分:1)

可以通过反射API安排通用方法,如下所示:

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