Substitute for Task<T>

6,166 views
Skip to first unread message

Steve Finn

unread,
Nov 3, 2013, 2:46:41 AM11/3/13
to nsubs...@googlegroups.com
From looking around it looks as though it is possible to use NSubstitute to unit test in Async/Await scenario. I can't find any docs for the syntax.

I have a Repository that I would normally substitute in a sync context as follows:
Repository.FindFirstByPredicate<Device>(Arg.Any<Expression<Func<Device, bool>>>()).Returns(new Device{ blah = blah blah});

My repository now has a FindFirstByPredicateAsync<T> method, how would I substitute for that which of course returns Task<T> or Task<Device> using the above example.


Any assistance is truly appreciated.

Best regards,
Steve

David Tchepak

unread,
Nov 3, 2013, 5:55:59 AM11/3/13
to nsubs...@googlegroups.com
No special syntax; just return the task you want. For example:

public interface IRepository
{
    Task<T> FindFirst<T>(Func<T, bool> pred);
}

[Test]
public async Task Async()
{
    var repository = Substitute.For<IRepository>();
    repository.FindFirst(Arg.Any<Func<int, bool>>()).Returns(Task.FromResult(42));

    var result = await repository.FindFirst<int>(x => true);

    Assert.That(result, Is.EqualTo(42));
}

Please let me know if you run into any problems with this.
Regards,
David


--
You received this message because you are subscribed to the Google Groups "NSubstitute" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nsubstitute...@googlegroups.com.
To post to this group, send email to nsubs...@googlegroups.com.
Visit this group at http://groups.google.com/group/nsubstitute.
For more options, visit https://groups.google.com/groups/opt_out.

Steve Finn

unread,
Nov 4, 2013, 3:53:43 AM11/4/13
to nsubs...@googlegroups.com
David,

Many many thanks for your reply. I wasn't aware of Task.FromResult !

Once again thx for your help.

Steve
Reply all
Reply to author
Forward
0 new messages