【问题标题】:Visual Studio 2008: Unit-Test methods in generic classes are not detected properlyVisual Studio 2008:未正确检测到泛型类中的单元测试方法
【发布时间】:2010-09-17 12:56:44
【问题描述】:

我有一堆存储库类,我想使用 Visual Studio 2008 对其进行单元测试。它们实现了以下接口:

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 可见,这又会导致冗余..

有没有更好的方法来解决这种痛苦?我不想用大量的包装代码弄乱我的测试:(

【问题讨论】:

    标签: c# visual-studio visual-studio-2008 unit-testing mstest


    【解决方案1】:

    是否可以在测试声明中没有泛型,而是单独依赖 IEntity,例如:

    IEntity GetById(int id);
    IEnumerable<IEntity> GetAll();
    

    如果这两个函数需要对 IEntity 进行任何实例化,您可以让 Repository 构造函数接受一个工厂对象。进行实例化将是工厂对象的工作。工厂将有一个抽象基(或接口),其实例化方法只返回一个 IEntity,以及可能会或可能不会被模板化的子类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 2013-06-07
      • 1970-01-01
      • 2012-11-14
      相关资源
      最近更新 更多