Moq.Mock&LT; T&GT; - 如何设置,它接受一个前pression的方法 [英] Moq.Mock<T> - how to setup a method that takes an expression
问题描述
我嘲笑我的仓库界面,我不知道如何设置,它接受一个前pression并返回一个对象的方法?我使用起订量和NUnit
接口:
public接口IReadOnlyRepository:IDisposable接口
{
IQueryable的&LT; T&GT;所有&LT; T&GT;()其中T:类;
T单&LT; T&GT;(防爆pression&LT;&Func键LT; T,BOOL&GT;&GT;前pression)其中T:类;
}
与IQueryable的已安装测试,但不知道如何设置T单:
私人Moq.Mock&LT; IReadOnlyRepository&GT; _mockRepos;
私人AdminController _controller;
[建立]
公共无效设置()
{
VAR所有页=新的List&LT;页面和GT;();
为(变量I = 0; I&小于10;我+ +)
{
allPages.Add(新页{ID = I,标题=页面标题+ I,弹头=页面 - 标题 - + I,CONTENT =页面+ I +上的页面内容。});
}
_mockRepos =新Moq.Mock&LT; IReadOnlyRepository&GT;();
_mockRepos.Setup(X =&GT; x.All&LT;页面和GT;())返回(allPages.AsQueryable());
//不知道这里做什么?
_mockRepos.Setup(X =&GT; x.Single&LT;页面和GT;()
// ----
_controller =新AdminController(_mockRepos.Object);
}
您可以设置它是这样的:
_mockRepos.Setup(X =&GT; x.Single&LT;第&GT;(It.IsAny&LT;防爆pression&LT; Func键&LT;页,布尔&GT;&GT;&GT;()) )//返回等等。
不过你是来补防的起订量的缺点之一。你会希望把一个实际的前pression存在,而不是使用 It.IsAny
,但起订量不支持设立称取前pressions与方法具体EX pressions(这是实现一个困难的功能)。困难来自其找出两位前pressions是否是等价的。
因此,在您的测试,你可以传递的任何的防爆pression&LT; Func键&LT;页,布尔&GT;&GT;
键,它会通过回到凡是你必须设置模拟返回。测试的值是稍微稀释。
I am Mocking my repository interface and am not sure how to setup a method that takes an expression and returns an object? I am using Moq and NUnit
Interface:
public interface IReadOnlyRepository : IDisposable
{
IQueryable<T> All<T>() where T : class;
T Single<T>(Expression<Func<T, bool>> expression) where T : class;
}
Test with IQueryable already setup, but don't know how to setup the T Single:
private Moq.Mock<IReadOnlyRepository> _mockRepos;
private AdminController _controller;
[SetUp]
public void SetUp()
{
var allPages = new List<Page>();
for (var i = 0; i < 10; i++)
{
allPages.Add(new Page { Id = i, Title = "Page Title " + i, Slug = "Page-Title-" + i, Content = "Page " + i + " on page content." });
}
_mockRepos = new Moq.Mock<IReadOnlyRepository>();
_mockRepos.Setup(x => x.All<Page>()).Returns(allPages.AsQueryable());
//Not sure what to do here???
_mockRepos.Setup(x => x.Single<Page>()
//----
_controller = new AdminController(_mockRepos.Object);
}
You can set it up like this:
_mockRepos.Setup(x => x.Single<Page>(It.IsAny<Expression<Func<Page, bool>>>()))//.Returns etc...;
However you are coming up against one of Moq's shortcomings. You would want to put an actual expression there instead of using It.IsAny
, but Moq doesn't support setting up methods that take expressions with specific expressions (it's a difficult feature to implement). The difficulty comes from having to figure out whether two expressions are equivalent.
So in your test you can pass in any Expression<Func<Page,bool>>
and it will pass back whatever you have setup the mock to return. The value of the test is a little diluted.
这篇关于Moq.Mock&LT; T&GT; - 如何设置,它接受一个前pression的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!