Skip to content

Intercept any call to a generic method when using Arg.AnyType as a generic argument #854

@JMolenkamp

Description

@JMolenkamp

I am trying to intercept any call to a generic method, regardless of the used generic argument. I expected that using Arg.AnyType as the generic argument would be the way to go, but that does not seem to be the case. As far as I can find out, what I want is currently not possible.

Below an example of what I am trying to achieve. Configure bar.Get<Arg.AnyType>.Returns(...) and then have the configured return delegate called when calling bar.Get<int>().

public interface IFoo<T> {};

public interface IBar
{
    IFoo<T> Get<T>();
}

[Test]
public void Sample()
{
    IBar bar = Substitute.For<IBar>();

    bar
        .Get<Arg.AnyType>()
        .Returns(x =>
        {
            // Somehow find out what the actual method call was, i.e. find out what T was
            // Create some IFoo<T> to return, possibly create a substitute and supply some setup
        });

    IFoo<int> foo = bar.Get<int>();
}

It doesn't seem to involve a whole lot to make this possible, but I have no idea what I'm overlooking. I will create a PR to show what I did.

Related links
634

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature-requestRequest for a new NSubstitute feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions