[英]WHERE statement does not work in unit test using It.IsAny
我对存储库的单元测试有一些问题,尤其是方法FindBy()
public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
{
return Entities.Where(predicate);
}
实体是IDbSet<T> Entities = _context.Set<T>();
我正在尝试在控制器中测试该方法,但是我总是在houses
得到NULL
。
您能给我些建议吗?
public override HttpResponseMessage Get()
{
var houses = Repository.FindBy(y => y.Year == DateTime.Now.Year);
if (houses != null && houses.Any())
{
return Request.CreateResponse(HttpStatusCode.OK, houses);
}
const string message = "House: No content";
return ErrorMsg(HttpStatusCode.NotFound, message);
}
这是我的测试方法
[TestMethod]
public void GetAll()
{ //Arrange
var houses = new List<House>
{
new House {ID = 1, BuildNr = "01", HouseNr = "001" },
new House {ID = 2, BuildNr = "02", HouseNr = "002" },
new House {ID = 3, BuildNr = "03", HouseNr = "003" },
new House {ID = 4, BuildNr = "04", HouseNr = "004" },
new House {ID = 5, BuildNr = "05", HouseNr = "005" }
};
var mock = new Mock<IRepository<T>>();
mock.Setup(m => m.FindBy(f => f.Year == It.IsAny<int>()))
.Returns(houses.AsQueryable());
//...
var controller = new HouseController(mock.Object);
//Action
var response = controller.Get();
var result = response.ContentToQueryable<T>();
//Assert
Assert.AreEqual(5, result.Count());
}
那不是使用It.IsAny的正确方法,IsAny旨在替代整个参数,而不是一个参数的一部分-在这种情况下,您可以像这样将它(某种方式)用于未指定的谓词:
mock.Setup(m => m.FindBy(It.IsAny<Expression<Func<int, bool>>>())
您已经知道控制器方法将使用当前年份,请使用该年份进行设置:
mock.Setup(m => m.FindBy(f => f.Year == DateTime.Now.Year))
然后,如果不小心将控制器方法更改为使用错误的值,则测试将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.