代码之家  ›  专栏  ›  技术社区  ›  Praveen Rao Chavan.G

如果向类添加泛型约束,则无法识别单元测试

  •  2
  • Praveen Rao Chavan.G  · 技术社区  · 8 年前

    我想在我的单元测试类中添加一个泛型约束

    public class CacheOperationsUnitTests<T>
    {
        private ITCache<T> ICacheStore;
        static readonly IUnityContainer container = new UnityContainer();
        static CacheOperationsUnitTests()
        {
            container.RegisterType(typeof(ITCache<>), typeof(TRedisCacheStore<>), (new ContainerControlledLifetimeManager()));
        }
    
        public CacheOperationsUnitTests()
        {
            ICacheStore = container.Resolve<TRedisCacheStore<T>>();
    
        }
    

    但是,当我这样做时,我的单元测试在测试资源管理器中无法识别,当我尝试运行单元测试时,会看到以下内容:

    f:\ projects\development vsto\trf dev(performance)new\perf\ssrprod\caching.unittests\bin\debug\caching.unittests.dll中没有可用的测试。请确保已注册测试发现程序和执行程序,并且平台和框架版本设置正确,然后重试。**

    当我移除 <T> 但我需要 <T & GT; 因为我的代码中需要它们:

    private ITCache<T> ICacheStore;
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   Marc Gravell    8 年前

    它不是一个 一般约束 这会伤害到你;一个通用的约束是 where T : SomeWhatever “部分-你没有。在这里伤害你的是 泛型类型参数 -也就是说,它本身就是通用的。

    想象一下你是一个试跑者。你可以看到

    public class SomeTests<T> {}
    

    它有看起来像测试的公共方法。现在;如何创建一个实例?什么 T 你选择吗?您不能创建开放泛型类型的实例-您需要一个具体的类型,如 SomeTests<Bar> (对于某些类型 Bar )

    一种选择可能是:

    public abstract class CacheOperationsUnitTests<T>
    public class FooCacheOperationsUnitTests : CacheOperationsUnitTests<Foo>
    public class BarCacheOperationsUnitTests : CacheOperationsUnitTests<Bar>
    // plus whatever other T you need
    

    但是,我强烈怀疑您可以简单地从测试中移除泛型,并使用特定的具体类型来代替 T