【问题标题】:C# Unit Testing - Actual: (null) Result using List in xUnit with Moq FrameworkC# 单元测试 - 实际:(null) 使用 xUnit 中的 List 和 Moq 框架的结果
【发布时间】:2018-11-17 10:31:29
【问题描述】:

早安,

我是在 C# 中使用 xUnit 和 Moq 框架进行单元测试的新手。

我正在尝试测试一个返回列表的方法,该方法负责从存储库类中的 Queryable 方法返回信息列表。

这是我的测试方法。

[Fact]
public void SelectInfoByName_InfoHasValue_ReturnInfoSelect()
{
    var service = new Mock<ISearchInfoRepository>();

    var selectInfo = new SelectInfoService(null, service.Object);

    service.Setup(s => s.SearchInfoByName("info")).Returns(new List<Info>
    {
        new Info{ Name = "name1",InfoId = 1},
        new Info{Name = "name2",InfoId = 2}
    }.AsQueryable);

    var expectedResult = new List<Info>
    {
        new Info{Name = "name1", InfoId = 1},
        new Info{Name = "name2", InfoId = 2}
    };

    var result = selectInfo.SelectInfoByName("info").Result;

    Assert.Equal(expectedResult, result);
}

这是我的SelectInfoByName,负责按名称返回信息列表

public async Task<IEnumerable<SearchSelect>> SelectInfoByName(string info)
{
    var infoByName = searchInfoRepo.SearchInfoByName(info);

    return await infoByName.Select(info => new SearchSelect
    {
        text = info.Name,
        value = info.InfoId
    }).ToListAsync();
}

最后,这是我使用 EF 与数据库通信的存储库或存储类。

// storage or repo class
public IQueryable<Info> SearchInfoByName(string info)
{
    return infoRepo.Info().Where(info => info.Name.Contains(name.Trim().ToLower()));
}

注意:从.AsyncState 更改为.Result,但实际值为null

提前谢谢你。

【问题讨论】:

    标签: c# mocking moq xunit xunit.net


    【解决方案1】:

    你会收到一条错误消息:

    The source IQueryable doesn’t implement IAsyncEnumerable. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.

    基于这个Blog post,他使用Task.FromResult来解决问题。所以你的服务代码应该是这样的:

    public async Task<IEnumerable<SearchSelect>> SelectInfoByName(string info)
    {
        var infoByName = searchInfoRepo.SearchInfoByName(info);
    
        return await Task.Result(infoByName.Select(info => new SearchSelect
        {
            text = info.Name,
            value = info.InfoId
        }).ToListAsync());
    }
    

    然后在你的任务方法中,尝试使用 Assert 计数长度而不是比较它们的值。

    Assert.True(expectedResult.Count(), result.Count());
    

    【讨论】:

      【解决方案2】:

      当你得到你的结果时,你要求 .AsyncState。

      要求 .Result 代替,以获得实际结果:

      var result = selectInfo.SelectInfoByName("info").Result;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-12
        • 1970-01-01
        • 2012-10-19
        • 1970-01-01
        • 2018-03-29
        • 1970-01-01
        相关资源
        最近更新 更多