Creating a Stub for a C # Generic Method

I have a general method: (simplified)

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

For testing purposes, I want to create a stub from which I want "Foo" to return 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 I have Tnot determined what type it is, I cannot return it List<Foo>. Compiler error. So, how can I write a stub for this kind of common method?

Edit: slightly changed the code. The first method will be retrieved from the database on the type parameter. The second is a stub for testing. Sorry I'm not sure if this explains what I want to mention.

Thank.

+3
source share
1 answer
    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>());
    }
}
+3
source

All Articles