0
votes

I am getting a NotSupportedException error message on my Unit Test using Moq.

I have the following test which mocks the result.

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 => x.Result.Total).Returns(total); <-- an exception is thrown

Invalid setup on a non-virtual (overridable in VB) member: mock => mock.Result

It works synchronously without any problems.

Any suggestions how to get around this exception?

How can I set it as virtual?

1

1 Answers

0
votes

You mock the Task<ISearchResponse<Person>> but not the ISearchResponse<Person> task result.

Here's an example of mocking a task result; you don't have all of the types that you're working with in your example so I've simplified this a little

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; }
}