0

I need to create a mock instance of a given DB, whose interface is a generic func<T>(param1, param2,...)

Thing is, I want to give a concrete answer for certain values and a certain value of T.

How can I achieve that? (I need a real regular class implementing that interface, and not an NSubstitute\Mock class)

I tried creating two functions, one with a generic signature, and one with a concrete signature, but the compiler doesn't seem to recognize it is an implementation of the same interface function)

public interface IManager
{
    T func<T>(string parameter);
}
openshac
  • 4,966
  • 5
  • 46
  • 77
  • Possible duplicate of [Mocking Generic Method with NSubstitute](https://stackoverflow.com/questions/17902491/mocking-generic-method-with-nsubstitute) – Tobias Tengler Aug 04 '19 at 15:23
  • The reference to NSubstitute was mistaken on my side. As I write later, I wish to create a concrete class which implements the interface at the end – Igor Smigor Aug 04 '19 at 15:30
  • 1
    If the interface method is generic, and you are mocking the interface, then you need to mock a generic method. It should be up to the code consuming the method to resolve the type parameter. If you think otherwise, please fix your question so it includes a good [mcve] showing exactly what you're trying to do, explain what that code does, what you want it to do instead, and what _specifically_ you are having trouble figuring out. – Peter Duniho Aug 04 '19 at 15:35
  • 2
    @IgorSmigor Can you reformat the question so we get a clearer picture of the current problem and what you are actually trying to do? Without a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) that clarifies your specific problem or additional details to highlight exactly what was done, it’s hard to reproduce the problem, allowing a better understanding of what is being asked. – Nkosi Aug 04 '19 at 15:44

1 Answers1

0

Suppose Foo is your "certain value of T". Simply instantiate an instance a concrete class that implements your interface.

IManager manager = new ConcreteManager()
Foo foo = manager.func<Foo>("input value");

where

public class ConcreteManager : IManager
{
    public T func<T>(string parameter)
    {
        // Implementation here

    }
}

Remember that the implementation is typically code that will work with any type T.

See the List class example: https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs

You don't really want to be having to do the following (although I sure you'll be able to find code that does).

    public T func<T>(string parameter)
    {
         Type listType = typeof(T);
         if(listType == typeof(int))
         {
             ...
         } 
         ...
    }
openshac
  • 4,966
  • 5
  • 46
  • 77