c# - WHERE 语句在使用 It.IsAny 的单元测试中不起作用

标签 c# asp.net linq unit-testing mocking

我的存储库的单元测试存在一些问题,特别是方法 FindBy()

public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
{
   return Entities.Where(predicate);
}

实体是 IDbSet<T> Entities = _context.Set<T>();

我正在尝试在 Controller 中测试该方法,但我总是得到 NULLhouses
您能给我一些建议吗?我应该用它做什么?

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 的正确方法,它旨在替换整个参数,而不是其中的一部分 - 在这种情况下,您将像这样将它(某物)用于未指定的谓词:

 mock.Setup(m => m.FindBy(It.IsAny<Expression<Func<int, bool>>>())

正如您已经知道 Controller 方法将使用当前年份,请使用它进行设置:

mock.Setup(m => m.FindBy(f => f.Year == DateTime.Now.Year))

然后,如果 Controller 方法被意外更改为使用错误的值,您的测试将会失败。

关于c# - WHERE 语句在使用 It.IsAny 的单元测试中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34177654/

相关文章:

c# - Hook SetConsoleCtrlHandler 时没有堆栈跟踪的 NullReferenceException

c# - 如何使用通用搜索获取实体列表

asp.net - MVC 4 Web API 区域 404 错误 : "The controller for path '/Jobs/Send' was not found or does not implement IController."

c# - 带有超链接列的 GridView

sql - SQL Server 中多个查找表的索引

c# - LINQ查询数据表,加入多个选择

c# - 我如何确定 IObservable<T> 上有多少/明确的订阅者?

c# - 晦涩的编译器的 lambda 表达式翻译

ASP.NET:如何使链接成为多行?

c# - 通过 IEnumerable 特征执行 Action<T>?