NSubstitute icon indicating copy to clipboard operation
NSubstitute copied to clipboard

Cannot mock an interface method that returns a generic collection with dynamic type

Open jeohearn opened this issue 2 years ago • 2 comments

Describe the bug

Get an exception when mocking an interface method that returns a generic collection with a dynamic type.

To Reproduce

The code below cannot execute without throwing an exception, i.e.

Exception thrown: 'NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException' in NSubstitute.dll ` public class Demo { public interface IAccess { Dictionary<string, dynamic>? Execute(string name, Dictionary<string, dynamic>? parameters); }

[Test]
public void MethodReturnsGenericCollectionHavingDynamicType()
{
    var access = Substitute.For<IAccess>();
    dynamic dyn = new ExpandoObject();
    dyn.Text = "value";
    Dictionary<string, dynamic> ret = new Dictionary<string, dynamic> {{"sp1", dyn}};
    access.Execute(Arg.Any<string>(), null).Returns(ret);  // Get exception documented earlier
    // Or
    SubstituteExtensions.Returns(access.Execute(Arg.Any<string>(), null), ret); // Get exception documented earlier

    // remaining code omitted

}

} ` Environment:

  • NSubstitute version: [e.g. 5.0..0]
  • NSubstitute.Analyzers version: [e.g. CSharp 1.0.16]
  • Platform: [e.g. .NET 7 project on Windows]

Additional context I have tried casting Dictionary<string, dynamic> to Dictionary<string, object> without success, i.e.

access.Execute(Arg.Any(), null).Returns((Dictionary<string, object>)ret);

as well as,

SubstituteExtensions.Returns(access.Execute(Arg.Any(), null), (Dictionary<string, object>)ret);

jeohearn avatar Oct 25 '23 20:10 jeohearn

Hi @jeohearn ,

Does the explanation in this thread cover the case you have found?

https://github.com/nsubstitute/NSubstitute/issues/144#issuecomment-309392522

dtchepak avatar Oct 27 '23 09:10 dtchepak

I used all the work around techniques from the thread mentioned but they did not resolve my issue. I had to abandon using NSubstitute in favor of stubs which I really wanted to avoid.

jeohearn avatar Oct 30 '23 22:10 jeohearn

Doubting if this a bug or if we need a support for dynamics. As I don't see any docs about dynamics, I'm tagging this a feature request. But please correct me if wrong.

304NotModified avatar Apr 29 '24 12:04 304NotModified

@304NotModified from https://github.com/nsubstitute/NSubstitute/issues/144#issuecomment-309392522 I think we don't have a way to address this. Will close for now; please re-open if anyone knows an implementation that will work for this.

dtchepak avatar Apr 30 '24 13:04 dtchepak

To avoid confusing, I'm marking this as not plannend instead of completed :)

304NotModified avatar Apr 30 '24 14:04 304NotModified