public interface ISearchService
{
Task<IEnumerable<ReferenceInfo>> SearchReferenceInfos(string keyword, string user);
}
创建单元测试时,我尝试用Moq来模拟接口
var mockSearchService = new Mock<ISearchService>();
mockSearchService.Setup(x => x.SearchReferenceInfos(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(
new List<ReferenceInfo>() { new ReferenceInfo() { //set properties } }
}.AsEnumerable());
并将其注入我的模型
var listReference = new ListReferencesViewModel(mockSearchService.Object);
然后,在我的模型中,我将此服务称为
public class ListReferencesViewModel
{
public ListReferencesViewModel(ISearchService searchService)
{
_searchService = searchService;
}
public async Task Method()
{
var task = _searchService.SearchReferenceInfos("xx", "xx");
RefTrouve = task.ConfigureAwait(false).GetAwaiter().GetResult()?.ToArray();
}
问题:RefTrouve
始终是空的List
。我认为我的方法不正确。
我也已经尝试过Return
,但它也返回空列表
答案 0 :(得分:0)
好吧,由于您的SearchReferenceInfos
返回Task<T>
public async Task Method()
{
var data = await _searchService.SearchReferenceInfos("xx", "xx");
}
为什么不将设置更改为
mockSearchService.Setup(x => x.SearchReferenceInfos(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.FromResult(new List<ReferenceInfo>()
{ new ReferenceInfo() { //set properties } }));