[英]How to mock a generic method to return concrete type?
I'm trying to mock the return type of a generic method to match a specific concrete type but I cannot seem to get the casting to work out: 我正在尝试模拟泛型方法的返回类型以匹配特定的具体类型,但是我似乎无法使转换生效:
public T Get<T>(string key)
{
if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
return GetGenericIsAuthenticatedResponse();
return default(T);
}
private static GenericIsAuthenticatedResponse GetGenericIsAuthenticatedResponse()
{
return new GenericIsAuthenticatedResponse
{
AuthCode = "1234",
Email = "email@email.com"
};
}
So my question is how can I get the mock method to return the GenericIsAuthenticatedResponse? 所以我的问题是如何获取模拟方法以返回GenericIsAuthenticatedResponse?
That does not work because of how generics work. 由于泛型是如何工作的,因此不起作用。 If you want to return a specific type, you need to provide a filter for
T
: 如果要返回特定类型,则需要为
T
提供过滤器:
public T Get<T>(string key) where T: GenericIsAuthenticatedResponse
Otherwise, don't use generics for the return type: 否则,请勿对返回类型使用泛型:
public object Get<T>(string key)
{
if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
return GetGenericIsAuthenticatedResponse();
return default(T);
}
If you are completely sure that T
will be GenericIsAuthenticatedResponse
(given it's a test), you can do this: 如果您完全确定
T
将是GenericIsAuthenticatedResponse
(假设是测试),则可以执行以下操作:
public T Get<T>(string key)
{
if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
return (T)GetGenericIsAuthenticatedResponse();
return default(T);
}
I applied some lateral thinking in the end (or bodge depending on your POV) and serialised/deserialised Json to achieve this: 最后,我运用了一些横向思考(或根据您的POV进行了调整),并对Json进行了序列化/反序列化以实现此目的:
public T Get<T>(string key)
{
if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
return JsonConvert.DeserializeObject<T>(GetGenericIsAuthenticatedResponse());
return default(T);
}
private static string GetGenericIsAuthenticatedResponse()
{
var r = new GenericIsAuthenticatedResponse
{
Username = "email.email.com",
AuthCode = "1234"
};
return JsonConvert.SerializeObject(r);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.