简体   繁体   English

表达 <Func<T, bool> &gt;与It.IsAny总是返回true

[英]Expression<Func<T, bool>> with It.IsAny always return true

I'm trying to create a generic testclass to test my generic controllers. 我正在尝试创建一个通用的测试类来测试我的通用控制器。 Everything is working fine except this: I have a method like this: 一切都工作正常,除了这个:我有一个像这样的方法:

private T GetSingle(Expression<Func<T, bool>> expression)

I'm trying to setup the test like so: 我正试图像这样设置测试:

var Guids = new[] { Guid.NewGuid(), Guid.NewGuid() };
var items = Guids.Select(x => new T {Id = x});
var mock = new Mock<IRepository<T>>();
mock.Setup(m => m.GetSingle(
    It.IsAny<Expression<Func<T, bool>>>()))
   .Returns(new T());

And execute the test like this: 并执行这样的测试:

var value = Repository.GetSingle(x=> x.Id == Guid.NewGuid());

This always return a new T. 总是会带来新的T.

Is my setup wrong? 我的设置错了吗?

You're instructing Moq to return the same exact instance (in this case, new T() ), any time GetSingle is invoked, regardless of the expression provided. 无论提供什么表达式,无论GetSingle调用GetSingle ,都指示Moq返回相同的实例(在本例中为new T() )。 What you actually want is for it to invoke that expression against items : 你真正想要的是它为items调用该表达式:

mock.Setup(m => m.GetSingle(It.IsAny<Expression<Func<T, bool>>>()))
   .Returns<Expression<Func<T, bool>>>(expression => items.AsQueryable().Single(expression));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM