模拟一个通用的受保护方法
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))
{
}
}
}
我正在尝试测试 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 提交了一张票。我会在发现任何内容后立即更新此 post。
泛型方法可以通过反射来排列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);
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 提交了一张票。我会在发现任何内容后立即更新此 post。
泛型方法可以通过反射来排列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);