-
-
Notifications
You must be signed in to change notification settings - Fork 802
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mocking with generic parameters not properly supported #996
Comments
At runtime, there is no such thing as a concrete value of type
Can you please be more precise here? What exactly do you mean by "will fail"? And what is All of that being said,
Not so: you can pass an mock.Setup(p => p.Get(It.IsAny<object>())).Returns(new InvocationFunc(invocation => ...)); |
Apologies, I misread part of your post. I missed the bit defining using Moq;
using System;
using System.Reflection;
public interface IFoo
{
Func<T, T> Get<T>(T index);
}
class Program
{
public static T Get<T>(T t) => t;
static void Main()
{
var mock = new Mock<IFoo>();
mock.Setup(m => m.Get(It.IsAny<It.IsAnyType>()))
.Returns(new InvocationFunc(invocation =>
{
var genericArg = invocation.Method.GetGenericArguments()[0];
var get = typeof(Program).GetMethod("Get", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericArg);
return Delegate.CreateDelegate(typeof(Func<,>).MakeGenericType(genericArg, genericArg), get);
}));
var fn = mock.Object.Get("42");
fn("42");
}
} |
I am trying to mock a method with generic parameters as described in this PR #908
It works with only the most basic cases showed in the example e.g:
This setup for instance will fail when attempting to cast the string argument to an It.IsAnyType:
Using object in the setup works:
But then there is no way to tell which type was actually passed in which makes it of very limited interest.
Can this be improved to support methods with generic return types? Otherwise you may want to make the limitations clearer.
The text was updated successfully, but these errors were encountered: