[英]Mocking generic return type in generic method with a expression
I have the following interface with a generic method.我有以下带有通用方法的接口。
public interface IRepository {
Task<TResult> GetByIdAsync<TResult>(
int id,
Expression<Func<Entity, TResult>> expression,
TResult defaultValue = default);
}
In some parts of the code expression returns Tuple and anonymous type.在代码表达式的某些部分返回元组和匿名类型。
Example例子
var _repository = ServiceProvider.GetRequiredService<IRepository>();
var data = await _repository.GetByIdAsync(id, pr => Tuple.Create(pr, pr.SelfRefObject));
var data = await _repository.GetByIdAsync(id, pr => new { pr.SelfRefObjectId });
Is it possible to mock the method so it returns specified value with mentioned types?是否可以模拟该方法,以便它返回指定类型的指定值?
Example例子
var _repositoryMock = new Mock<IRepository>();
var anonymousReturnValue = new { SelfRefObjectId = 1 };
_repositoryMock
.Setup(pr => pr.GetByIdAsync(
entityId,
pr => new { pr.SelfRefObjectId },
default))
.ReturnsAsync(anonymousReturnValue)
.Verifiable();
var tupleReturnValue = Tuple.Create(new Entity(), new Entity());
_repositoryMock
.Setup(pr => pr.GetByIdAsync(
entityId,
pr => Tuple.Create(pr, pr.SelfRefObject),
default))
.ReturnsAsync(tupleReturnValue)
.Verifiable();
Thanks in advance.提前致谢。
In short: according to my knowledge you can't do this.简而言之:据我所知,你不能这样做。
There are two really useful helper types: It.IsAnyType
and It.IsSubType<T>
.有两种非常有用的辅助类型:
It.IsAnyType
和It.IsSubType<T>
。
During the setup phase you could use them to tell that your function accepts anything:在设置阶段,您可以使用它们来告诉您的函数接受任何内容:
_repositoryMock
.Setup(repo => repo.GetByIdAsync(
It.IsAny<int>(),
It.IsAny<Expression<Func<Entity, It.IsAnyType>>>(),
It.IsAny<It.IsAnyType>()))
.Verifiable();
Or it accepts only anonymous type or tuple:或者它只接受匿名类型或元组:
_repositoryMock
.Setup(repo => repo.GetByIdAsync(
It.IsAny<int>(),
It.Is<Expression<Func<Entity, It.IsAnyType>>>((o, type) => type.IsAnonymousType()),
It.Is<It.IsAnyType>((o, type) => type.IsAnonymousType())))
.Verifiable();
_repositoryMock
.Setup(repo => repo.GetByIdAsync(
It.IsAny<int>(),
It.Is<Expression<Func<Entity, It.IsAnyType>>>((o, type) => type.IsTuple()),
It.Is<It.IsAnyType>((o, type) => type.IsTuple())))
.Verifiable();
Helper methods:辅助方法:
public static class TypeExtension
{
public static bool IsAnonymousType(this Type type)
{
var hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any();
var nameContainsAnonymousType = type.FullName != null && type.FullName.Contains("AnonymousType");
return hasCompilerGeneratedAttribute && nameContainsAnonymousType;
}
public static bool IsTuple(this Type type)
{
if (!type.IsGenericType) return false;
var openType = type.GetGenericTypeDefinition();
return openType == typeof(Tuple<>) || openType == typeof(Tuple<,>)
|| openType == typeof(ValueTuple<>) || openType == typeof(ValueTuple<,>);
}
}
The problem comes when you need to specify the Return/ReturnAsync
part.当您需要指定
Return/ReturnAsync
部分时,问题就出现了。
_repositoryMock
.Setup(repo => repo.GetByIdAsync(
It.IsAny<int>(),
It.Is<Expression<Func<Entity, It.IsAnyType>>>((o, type) => type.IsTuple()),
It.Is<It.IsAnyType>((o, type) => type.IsTuple())))
.Returns(valueFunction: () => Task.FromResult(tupleReturnValue));
It won't compile because it can't convert Tuple<Entity, Entity>
to Mock.It.IsAnyType
它不会编译,因为它不能将
Tuple<Entity, Entity>
转换为Mock.It.IsAnyType
Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Tuple<anonym.Entity, anonym.Entity>>' to 'System.Threading.Tasks.Task<Moq.It.IsAnyType>'
严重性代码描述项目文件行抑制状态错误 CS0029 无法将类型“System.Threading.Tasks.Task<System.Tuple<anonym.Entity, anonym.Entity>>”隐式转换为“System.Threading.Tasks.Task<Moq.It .IsAnyType>'
Even the related github issue is closed the Type resolver does not seems to work.即使相关的github 问题已关闭,类型解析器似乎也不起作用。
Alternative approach could be making use of DefaultValueProvider
. 替代方法可以使用
DefaultValueProvider
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.