c# - Visual Studio 2008 : Unit-Test methods in generic classes are not detected properly

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

我有一堆存储库类,我想使用 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/

相关文章:

c# - 将整数数组转换为逗号分隔的字符串

C# 替换字符串的一部分

c# - 任务还没有开始调用Task.wait可能不会等待?

c++ - 是否可以从 CUDA 10.1 内核调用 cuBLAS 或 cuBLASLt 函数?

visual-studio - 我正在上一门类(class),但讲师说的东西行不通

c# - Winforms 控件不会显示

c# - 在 C# 和 Windows 窗体中调整面板大小

visual-studio-2008 - 用于删除 SourceSafe 绑定(bind)的实用程序?

c# - 什么是以及如何修复 System.TypeInitializationException 错误?

c# - 报表查看器的初学者教程?