Skip to content
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

How to argument match the generic parameter of a Func<T> with generic constraints? #767

Open
cado1982 opened this issue Jan 12, 2024 · 0 comments
Labels
question Question on NSubstitute behaviour

Comments

@cado1982
Copy link

Question
Hello. I am trying to mock out this method so that any time it is called the Func is invoked and T is returned.

T New<T>(Func<T> instantiate) where T : Command;

Command is a base class for all of my commands. I thought I could do this

harness.CommandFactory
            .New(Arg.Any<Func<Command>>())
            .Returns(r => r.Arg<Func<Command>>()());

But of course this only matches if the caller passes in the base Command, not a derived class such as AddUserCommand.

Then I came across the newly added Arg.AnyType and thought this was perfect for my needs but I can't get the syntax right. The remark on the method comments seems to indicate that I need to create a derived class but I'm not sure I can for this specific case... "If the generic type parameter has constraints, you will have to create a derived class/struct that implements those constraints." This was the attempt, it fails because now I am back to having a derived type which never matches

public record AnyCommand : Command, Arg.AnyType;

harness.CommandFactory
            .New(Arg.Any<Func<AnyCommand>>())
            .Returns(r => r.Arg<Func<Command>>()());

Does anyone have an idea how/if this can be achieved?

Related links

@304NotModified 304NotModified added the question Question on NSubstitute behaviour label Apr 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question on NSubstitute behaviour
Projects
None yet
Development

No branches or pull requests

2 participants