C#单元测试-实际:(空)结果使用xUnit中的列表和Moq框架
你好 我是C#中使用xUnit和Moq框架进行单元测试的新手 我试图测试一个方法,其中它返回list,该方法负责从repository类中的Queryable方法返回信息列表 这是我的测试方法C#单元测试-实际:(空)结果使用xUnit中的列表和Moq框架,c#,mocking,moq,xunit,xunit.net,C#,Mocking,Moq,Xunit,Xunit.net,你好 我是C#中使用xUnit和Moq框架进行单元测试的新手 我试图测试一个方法,其中它返回list,该方法负责从repository类中的Queryable方法返回信息列表 这是我的测试方法 [Fact] public void SelectInfoByName_InfoHasValue_ReturnInfoSelect() { var service = new Mock<ISearchInfoRepository>(); var selectInfo = ne
[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);
}
最后,这里是我的存储库或存储类,它使用EF与数据库通信
// storage or repo class
public IQueryable<Info> SearchInfoByName(string info)
{
return infoRepo.Info().Where(info => info.Name.Contains(name.Trim().ToLower()));
}
//存储或repo类
公共IQueryable SearchInfoByName(字符串信息)
{
返回infoRepo.Info(),其中(Info=>Info.Name.Contains(Name.Trim().ToLower());
}
注意:从.AsyncState
更改为.Result
,但实际值仍然是null
先谢谢你 当您得到结果时,您会请求.AsyncState 改为询问.Result,以获得实际结果:
var result = selectInfo.SelectInfoByName("info").Result;
您将在错误消息中看到该特定的错误:
源IQueryable未实现IAsyncEnumerable。只有实现IAsyncEnumerable的源才能用于实体框架异步操作。
基于此,他使用了任务.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());
}
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.True(expectedResult.Count(), result.Count());