0

Hi guys I have a method like this:

public virtual async Task StartSearch()
{
    CancellationTokenSource = new CancellationTokenSource();
    Context = ContextFactory.Create();

    SearchResults = await Task.Factory.StartNew(() =>
    {
        try
        {
            IsLoading = true;

            var resultTask = GetResults().ToListAsync(CancellationTokenSource.Token);

            while (!resultTask.IsCompleted && !resultTask.IsFaulted &&
                   !CancellationTokenSource.Token.IsCancellationRequested)
                Thread.Sleep(100);

            IsLoading = false;

            if (resultTask.IsFaulted)
                throw resultTask.Exception ??
                      new Exception("Some error.");

            return resultTask.IsCompleted && !resultTask.IsCanceled ? resultTask.Result : null;
        }
        catch (Exception)
        {
            IsLoading = false;
            throw;
        }
    }, CancellationTokenSource.Token) ?? SearchResults;
}

I wonder how could I mock up a Task (with all those IsFaulted, IsCompleted, IsCaneled fields) which I get from .ToListAsync() method? I've found that they are not virtual so I cannot create a Task object to simply mock them. Additional question is if it gives me something if I create my own dummy class and mock it for a test.

What are your suggestions? Maybe you don't want to mock it?

For now I only tested this to check if my method will return some data.

EDIT:

public abstract IQueryable<dynamic> GetResults();

and some exemplary implementation:

public override IQueryable<dynamic> GetResults()
{
    var query = Context.Table.AsQueryable();

    query = string.IsNullOrWhiteSpace(Field)
        ? query
        : query.Where(table => table.Field.Contains(SomeFilter));

    return query.Select(
            table => new
            {
                table.Field1,
                table.Field2,
                table.Field3
            }).OrderBy(table => table.Id);
}
  • Why are you polling the task returned by `ToListAsync` instead of just awaiting it? If you want to simulate a failed/cancelled operation you can mock the call and use a task returned by `Task.FromException` or `Task.FromCancelled` in your tests. – Lee Feb 03 '20 at 15:48
  • How does `GetResults()` method look like? – Pavel Anikhouski Feb 03 '20 at 17:32
  • @PavelAnikhouski I've added this code to the original post. – Piotr Zieliński Feb 04 '20 at 08:35
  • You can have a look at this [thread](https://stackoverflow.com/questions/7048511/mocking-classes-that-implement-iqueryable-with-moq/8533489), how to mock `IQueryable` interface – Pavel Anikhouski Feb 04 '20 at 08:50

0 Answers0