NSubstitute ambiguous call when following documentation example (but with async method)

The compiler error in your question looks like you are calling something that returns Task rather than Task<T>? This sample works for me:

public interface ISample {
    Task DoStuff(string name);
}

[Test]
public async Task SampleTest()
{
    var sample = Substitute.For<ISample>();
    sample.DoStuff("test").Returns(x => { throw new Exception("doh"); });
    // ...
}

I tend to get that error when I have a generic Task<T>, which can be fixed by specifying the return type in the .Returns() call like this:

public interface IRepository {
    Task<int> FindId(string name);
}

[Test]
public async Task SampleTest2()
{
    var sample = Substitute.For<IRepository>();
    sample.FindId("test").Returns<int>(x => { throw new Exception("doh"); });
    // ...
}

In the example above I've removed the ambiguity by using .Returns<int>(...) which will pick the first overload mentioned in the compiler error.

If that does not help could you post the signature of the method being tested?


Adding to Davids accepted answer if you want the Task method because your method does actually return a Task then you simply need to specify Returns<Task>.

object.Method().Returns<Task>(x => { throw new Exception("You messed up"); });

It's not necessary to specify the full return type i.e. don't do this -> Task<IEnumerable<YourClass>>