设置一个模拟的 EF 服务方法
Setup a mocked EF Service method
我的 NewsDataService 中有以下方法 class
public IEnumerable<NewsModel> GetImportantNews()
{
var result = this.newsfeedRepository.GetAll(
x => x.IsImportant == true,
x => new NewsModel()
{
Creator = x.User.UserName,
AvatarPictureUrl = x.User.AvatarPictureUrl,
Content = x.Content,
CreatedOn = x.CreatedOn
})
.OrderByDescending(x => x.CreatedOn);
return result;
}
我的问题是...
如何设置模拟服务方法 (GetImportantNews
),
所以它 returns 是 NewsModel
的列表,它们是 "Important"?
我的想法是这样的,但目前还行不通,因为它总是返回完整列表。
var expectedResult = new List<Newsfeed>()
{
new Newsfeed()
{
IsImportant = false,
},
new Newsfeed()
{
IsImportant = true
}
};
mockedNewsfeedRepository
.Setup(x => x.GetAll(
It.IsAny<Expression<Func<Newsfeed, bool>>>(),
It.IsAny<Expression<Func<Newsfeed, NewsModel>>>()
)).Returns(expectedResult);
基本上我想要的是我的 "expectedResult" 被方法中的逻辑过滤。
您可以在返回值时访问调用参数。使用 linq 将谓词和投影表达式参数应用于伪数据源,如下例所示。
mockedNewsfeedRepository
.Setup(x => x.GetAll(
It.IsAny<Expression<Func<Newsfeed, bool>>>(),
It.IsAny<Expression<Func<Newsfeed, NewsModel>>>()
))
// access invocation arguments when returning a value
.Returns((Expression<Func<Newsfeed, bool>> predicate, Expression<Func<Newsfeed, NewsModel>> projection) =>
expectedResult.Where(predicate.Compile()).Select(projection.Compile())
);
我的 NewsDataService 中有以下方法 class
public IEnumerable<NewsModel> GetImportantNews()
{
var result = this.newsfeedRepository.GetAll(
x => x.IsImportant == true,
x => new NewsModel()
{
Creator = x.User.UserName,
AvatarPictureUrl = x.User.AvatarPictureUrl,
Content = x.Content,
CreatedOn = x.CreatedOn
})
.OrderByDescending(x => x.CreatedOn);
return result;
}
我的问题是...
如何设置模拟服务方法 (GetImportantNews
),
所以它 returns 是 NewsModel
的列表,它们是 "Important"?
我的想法是这样的,但目前还行不通,因为它总是返回完整列表。
var expectedResult = new List<Newsfeed>()
{
new Newsfeed()
{
IsImportant = false,
},
new Newsfeed()
{
IsImportant = true
}
};
mockedNewsfeedRepository
.Setup(x => x.GetAll(
It.IsAny<Expression<Func<Newsfeed, bool>>>(),
It.IsAny<Expression<Func<Newsfeed, NewsModel>>>()
)).Returns(expectedResult);
基本上我想要的是我的 "expectedResult" 被方法中的逻辑过滤。
您可以在返回值时访问调用参数。使用 linq 将谓词和投影表达式参数应用于伪数据源,如下例所示。
mockedNewsfeedRepository
.Setup(x => x.GetAll(
It.IsAny<Expression<Func<Newsfeed, bool>>>(),
It.IsAny<Expression<Func<Newsfeed, NewsModel>>>()
))
// access invocation arguments when returning a value
.Returns((Expression<Func<Newsfeed, bool>> predicate, Expression<Func<Newsfeed, NewsModel>> projection) =>
expectedResult.Where(predicate.Compile()).Select(projection.Compile())
);