我有一堆存储库类,我想使用 Visual Studio 2008 对其进行单元测试。它们实现了以下接口(interface):
public interface IRepository<TEntity> where TEntity : IEntity
{
/// <summary>
/// Get entity by ID
/// </summary>
/// <param name="id">The ID</param>
/// <returns></returns>
TEntity GetById(int id);
/// <summary>
/// Get all entities
/// </summary>
/// <returns></returns>
IEnumerable<TEntity> GetAll();
}
现在我可以为我拥有的每个存储库编写一个完全成熟的测试类。但是,为了尽量减少冗余,我想编写一个包含主要“通用”测试方法的基本测试类。这将允许我为每个存储库编写一个简单的子类,如下所示:
[TestClass]
public class EmployeeRepositoryTest : RepositoryTestBase<Employee>
{
// all test methods are inherited from the base class
// additional tests could be added here...
}
但是,在 RepositoryTestBase 中定义的测试方法不会被 Visual Studio 检测到(因为泛型),使得这种方法无用。为了让它工作,我需要包装基类的每个方法,使它们对 Visual Studio 可见,这又会导致冗余..
是否有更好的方法来解决这种痛苦?我不想用大量的包装代码弄乱我的测试:(
最佳答案
是否可以在测试声明中不使用泛型,而是单独依赖 IEntity,例如:
IEntity GetById(int id);
IEnumerable<IEntity> GetAll();
如果这两个函数需要对 IEntity 进行任何实例化,您可以让 Repository 构造函数接受一个工厂对象。进行实例化将是工厂对象的工作。工厂将有一个抽象基础(或接口(interface)),其实例化方法仅返回一个 IEntity,以及可能模板化或不模板化的子类。
关于c# - Visual Studio 2008 : Unit-Test methods in generic classes are not detected properly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3735472/