我在使用Moq进行单元测试时收到NotSupportedException错误消息。
我有以下测试模拟结果。
public class Person
{
public string Id { get; set; }
}
[Test]
public void List_Should_List_All_People()
{
//Arrange
const long total = 3;
var list = new List<Person>();
var queryResponse = new Mock<Task<ISearchResponse<Person>>>();
queryResponse.Setup(x => x.Result.Total).Returns(total);
for (var i = 0; i < total; i++)
{
list.Add(new Person { Id = Guid.NewGuid().ToString() });
}
queryResponse.Setup(x => x.Result.Documents).Returns(list);
Thread.Sleep(2000);
_elasticClient.Setup(x => x.SearchAsync(It.IsAny<Func<SearchDescriptor<Person>, ISearchRequest>>())).Returns(queryResponse.Object);
// Act
var response = _repository.List<Person>();
//Assert
response.Count().Should().Be(3);
}
queryResponse.Setup(x =&gt; x.Result.Total).Returns(total); &lt; - 抛出异常
非虚拟(VB中可覆盖)成员的设置无效:mock =&gt; mock.Result
它同步工作没有任何问题。
有关如何解决此异常的任何建议吗?
如何将其设置为虚拟?
答案 0 :(得分:0)
您模拟Task<ISearchResponse<Person>>
但不是ISearchResponse<Person>
任务结果。
这是模拟任务结果的一个例子;你不具备你在你的例子中使用的所有类型,所以我已经简化了这一点
async void Main()
{
var elasticClient = new Mock<IElasticClient>();
//Arrange
const long total = 3;
var list = new List<Person>();
for (var i = 0; i < total; i++)
{
list.Add(new Person { Id = Guid.NewGuid().ToString() });
}
var searchResponse = new Mock<ISearchResponse<Person>>();
searchResponse.Setup(x => x.Total).Returns(total);
searchResponse.Setup(x => x.Documents).Returns(list);
_elasticClient.Setup(x => x.SearchAsync(It.IsAny<Func<SearchDescriptor<Person>, ISearchRequest>>()))
.ReturnsAsync(searchResponse.Object);
// Act
var response = await elasticClient.Object.SearchAsync<Person>(s => s.MatchAll());
//Assert
// outputs 3
Console.WriteLine(response.Documents.Count());
}
public class Person
{
public string Id { get; set; }
}