nsubstitute / NSubstitute

A friendly substitute for .NET mocking libraries.
https://nsubstitute.github.io
Other
2.67k stars 263 forks source link

Ambiguous method call for Task of nullable types #725

Open FNERNST opened 1 year ago

FNERNST commented 1 year ago

Describe the bug When using the Returns extension method with a Task that may contain a nullable value, the method is ambiguous. The same happens for non primitive nullable types. See the example below which results in a compilation error.

To Reproduce

public interface ITest 
{
  Task<int?> TestAsync();
}

var test = Substitute.For<ITest>();
test.TestAsync().Returns(Task.FromResult(1));

Expected behaviour The correct Returns method is called.

Environment:

304NotModified commented 6 months ago

I can confirm this issue:

image

The issue is that Task.FromResult(1); will create a Task<int> and not a Task<int?>

y0ung3r commented 1 month ago

Hi, @FNERNST, @304NotModified

I don't think this is an NSubstitute problem. And I don't think it is a problem at all.

By using Task.FromResult and passing 1 there, you are telling it that you intend to use the int type. It's impossible for the compiler to get a value with type int? by passing just the value 1. You need to ask the compiler to use the int? type explicitly.

Try something like this:

test.TestAsync().Returns(Task.FromResult<int?>(1));

Screenshot:

image

cremor commented 1 month ago

Why do you even write Task.FromResult? You can simply write test.TestAsync().Returns(1); and NSubstitute will wrap it in a task for you. This even works with the nullable example.