Mocking Generic Method with NSubstitute
Asked Answered
K

1

12

I have an interface with a number of generic methods. These methods perform operations based on the type of data that is passed in. How do I mock this with NSubstitute? At the moment, I had to resort to using a concrete class instead of a mock since I cannot handle all possible types that the method will be called with.

public interface IInstanceSource
{
    bool CanCreate<T>();
    T Create<T>();
    void Register<T>(Func<T> creator);
}

    public static IInstanceSource GetInstanceSource()
    {
        var _data = new Dictionary<Type, Func<object>>();
        var a = Substitute.For<IInstanceSource>();
        //code below fails since T is not defined. How do I make the code below accept any type?
        a.WhenForAnyArgs(x=>x.Register(Arg.Any<Func<T>>)).Do(x=> { /* todo */});
        a.CanCreate<T>().Returns(x => _data[typeof (T)]);
        return a;
    }

thanks.

Karlise answered 27/7, 2013 at 21:10 Comment(0)
C
10

NSubstitute doesn't support setting up multiple instances of a generic method automatically.

The way we'd normally see IInstanceSource used in a test is to configure it for a specific bit of code under test, so T would be known. If a single fixture needed to work for a few different Ts, we could make configuration simpler by having a helper method like ConfigureInstanceSource<T>() which would do the configurations steps for a specific T.

In your case though it seems like you want a fixed behaviour for all fake instances of IInstanceSource, in which case I believe you are going the right way about it by hand-coding your own test double.

Cattail answered 28/7, 2013 at 12:31 Comment(1)
Thanks. I had to write a class that implements IInstanceSource. It works just fine. I though maybe it was supported by default and I had not seen it.Karlise

© 2022 - 2024 — McMap. All rights reserved.