使用Where()返回Moq

时间:2014-12-19 01:38:36

标签: c# unit-testing moq

我试图设置一个模拟来从集合中返回数据:

    private IList<DutyCategory> dutyCategories;
    private Mock<IDutyCategoryService> mockService;

    [TestInitialize()]
    public void UnitTestSetup()
    {
        dutyCategories = new List<DutyCategory>()
        {
            new DutyCategory(){Description = "Description",ID = 1,IsActive = true,Name = "Test 1",OrganizationID = 1}
        };
        mockService = new Mock<IDutyCategoryService>();
        mockService.Setup(a => a.GetDutyCategories()).ReturnsAsync(dutyCategories);
        mockService.Setup(a => a.GetDutyCategoriesByOrganization(It.IsAny<int>()))
            .ReturnsAsync((int id) => dutyCategories.Where(n=>n.OrganizationID == id));
    }

UnitTestSetup中的最后一行是问题所在。我收到以下错误:

  

无法将lambda表达式转换为&#39; System.Collections.Generic.IEnumerable&#39;因为它不是委托类型

如何模拟GetDutyCategoriesByOrganization以便返回列表dutyCategories的子集?

1 个答案:

答案 0 :(得分:0)

这似乎有效:

 .Returns<int>(i => Task.FromResult(dutyCategories.Where(n => n.OrganizationID == i)));