Moq引发异常,表明表达式树可能不包含使用可选参数的调用或调用

问题描述 投票:0回答:1

我正在编写NUnit测试用例。我正在编写测试用例以获得一些价值。下面是我的设置。

[Test]
public async Task GetGeographyList_StateUnderTest_ExpectedBehavior()
{
    // Arrange
    var geographyBusinessLogic = this.CreateGeographyBusinessLogic();

    Geography geographyObj = new Geography() { Id = 101, Country = "India", Region = "APAC", SubRegion = "Asia South" };
    IEnumerable<Geography> geographyObjList =  new List<Geography>() { geographyObj };
    //this.geographyRepository.setupGetAsync<Geography>(geographyObjList);
    this.geographyRepository.Setup(
        x => x.GetAsync()).ReturnsAsync(geographyObjList);

    // Act
    var result = await geographyBusinessLogic.GetGeographyList();

    // Assert
    Assert.IsNotNull(result);
}

在上面的代码中,x => x.GetAsync()引发错误:

表达式树可能不包含使用可选参数的调用或调用

下面是我对geographyBusinessLogic.GetGeographyList()的实现:

public async Task<IEnumerable<GeographyEntity>> GetGeographyList()
{
    var listOfGeographies = await this.GeographyRepository.GetAsync().ConfigureAwait(false);

    IEnumerable<GeographyEntity> result = from o in listOfGeographies
                                          select new GeographyEntity
                                          {
                                            Id = o.Id,
                                            Country = o.Country,
                                            Region = o.Region,
                                            SubRegion = o.SubRegion
                                          };
    return result;
}

下面是GetAsync方法的实现:

public async Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, params Expression<Func<T, object>>[] includes)
{
    IQueryable<T> query = this.dbSet;
    foreach (Expression<Func<T, object>> include in includes)
    {
        query = query.Include(include);
    }

    if (filter != null)
    {
        query = query.Where(filter);
    }

    if (orderBy != null)
    {
        query = orderBy(query);
    }

    return await query.ToListAsync().ConfigureAwait(false);
}

有人可以帮助我理解此错误,有人可以告诉我我在这里缺少什么吗?任何帮助将不胜感激。

c# .net nunit moq
1个回答
1
投票

设置模拟程序时,您需要填写所有可选参数。例如:

this.geographyRepository.Setup(x => x.GetAsync(
    It.IsAny<Expression<Func<Geography, bool>>>(),
    It.IsAny<Func<IQueryable<Geography>, IOrderedQueryable<Geography>>>(),
    It.IsAny<Expression<Func<Geography, object>>[]>())).ReturnsAsync(geographyObjList);
© www.soinside.com 2019 - 2024. All rights reserved.