NSubstitute
NSubstitute copied to clipboard
Cannot mock an interface method that returns a generic collection with dynamic type
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
as well as,
SubstituteExtensions.Returns(access.Execute(Arg.Any
Hi @jeohearn ,
Does the explanation in this thread cover the case you have found?
https://github.com/nsubstitute/NSubstitute/issues/144#issuecomment-309392522
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.
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 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.
To avoid confusing, I'm marking this as not plannend instead of completed :)