【发布时间】:2014-09-18 18:17:49
【问题描述】:
如何为这个方法编写单元测试:
public void ClassifyComments()
{
IEnumerable<Comment> hamComments = _commentRepository.FindBy(x => x.IsSpam == false);
IEnumerable<Comment> spamComments = _commentRepository.FindBy(x => x.IsSpam == true);
//....
}
FindBy 方法将表达式作为参数:
public virtual IEnumerable<T> FindBy(Expression<Func<T, bool>> filter)
{
return dbSet.Where(filter).ToList();
}
这是我目前的单元测试:
IEnumerable<Comment> spamComments = Builder<Comment>.CreateListOfSize(10).All()
.With(x => x.Content = "spam spam spam")
.Build();
IEnumerable<Comment> hamComments = Builder<Comment>.CreateListOfSize(10).All()
.With(x => x.Content = "ham ham ham")
.Build();
var mockRepository = new Mock<IGenericRepository<Comment>>();
mockRepository
.Setup(x => x.FindBy(It.Is<Expression<Func<Comment, bool>>>(y => y.IsSpam == true)))
.Returns(spamComments);
mockRepository
.Setup(x => x.FindBy(It.Is<Expression<Func<Comment, bool>>>(y => y.IsSpam == true)))
.Returns(hamComments);
但我无法编译它,如何更改此测试,以便模拟生成 hamComments 和 spamComments 的值。
错误 2 'System.Linq.Expressions.Expression>' 不包含“IsSpam”的定义和扩展方法 'IsSpam' 接受类型的第一个参数 'System.Linq.Expressions.Expression>' 可以找到(您是否缺少 using 指令或程序集 参考?)
【问题讨论】:
-
您的单元测试似乎没有多大意义,如果
FindBy是IGenericRepository<T>上的一个方法,那么您为什么要创建您要测试的系统的模拟实例? -
我不想测试 GenericRepository 类的 FindBy 方法。我需要在方法 ClassifyComments 中为第一个和第二个 FindBy 设置返回值。
-
你用的是什么模拟框架?
-
我使用 AutoMoq。如果我在方法 ClassifyComments 中只有一个 FindBy,我可以使用 AutoMoq 中的 It.IsAny。不幸的是,我有两个具有不同参数的 FindBy。
标签: c# unit-testing moq automoq