3

I have a generic method: (simplified)

public class DataAccess : IDataAccess
{
    public List<T> GetEntity<T>()
    {
       return GetFromDatabase<T>(); //Retrieve from database base on Type parameter
    }
}

For testing purpose, I want to create a stub from which I want 'Foo' should be returned with some data:

public class DataAccessStub : IDataAccess
{
    public List<T> GetEntity<T>()
    {
       List<Foo> listFoo = new List<Foo>();
       Foo foo = new Foo();
       foo.Name = "Some Name";
       listFoo.Add(foo);

       return listFoo; // I want Foo to be returned
    }
}

Since T has not identified what type it is yet, I can't return List<Foo>. Compiler error will occur. So How can I write a stub for this kind of generic method?

Edit: Changed the code a little bit. The first method will retrieve from the database base on Type Parameter. The second is a stub for testing. Sorry that I am not sure if this explain what I want to mention.

Thanks.

TMS
  • 75
  • 2
  • 9

1 Answers1

3
    interface IA
{
    List<T> Get<T>();
}

class StubA : IA
{
    public List<T> Get<T>()
    {
        var item = new Foo();
        var data = new List<Foo> {item};
        return new List<T>(data.Cast<T>());
    }
}
Ivan Danilov
  • 14,287
  • 6
  • 48
  • 66