Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Rhino模拟存根返回与预期不同的类型,并破坏了我的单元测试_C#_Unit Testing_Rhino Mocks - Fatal编程技术网

C# Rhino模拟存根返回与预期不同的类型,并破坏了我的单元测试

C# Rhino模拟存根返回与预期不同的类型,并破坏了我的单元测试,c#,unit-testing,rhino-mocks,C#,Unit Testing,Rhino Mocks,与昨天的有关。我实现了由提出的,但这导致了另一个问题。 总而言之:我有一个类包含一个Type->IList字典,例如Cat->{cat1,cat2},Zebra->{zebra1,zebra2}其中Cat和Zebra是动物的子类。现在提出以下方法来检索特定类型的所有动物: IList<T> GetAnimalsOfType<T>() where T : Animal { return dictionary[typeof(T)].OfType<T>().

与昨天的有关。我实现了由提出的,但这导致了另一个问题。 总而言之:我有一个类包含一个
Type->IList
字典,例如
Cat->{cat1,cat2},Zebra->{zebra1,zebra2}
其中
Cat
Zebra
动物的子类。现在提出以下方法来检索特定类型的所有动物:

IList<T> GetAnimalsOfType<T>() where T : Animal {
    return dictionary[typeof(T)].OfType<T>().ToList();
}
IList GetAnimalsOfType(),其中T:Animal{
返回类型()的字典[typeof(T)]。ToList();
}
这可以工作,但破坏了我的单元测试。原因是Animal是一个抽象类,所以我用它来存根(使用
Animal=MockRepository.generateSub是一个动物代理,我要求使用Animal,这打破了我的测试。有没有关于如何纠正这种情况的建议


更新:感谢所有人提供的解决方案。

由于编译器需要提前知道类型,因此您无法使用此选项:

zoo.AddAnimal(animal);  
IList<Animal> animals= zoo.GetAnimalsOfType<typeof(animal)>();  
Assert.That(animals[0], Is.EqualTo(animal));
这并不奇怪,因为您希望
GetAnimalsOfType
只返回确切类型的动物,不是吗?如果您这样做:

class Tiger : Animal
{
}

zoo.AddAnimal(new Tiger());  
IList<Animal> animals= zoo.GetAnimalsOfType<Animal>();

我想不会。如果你想做你概述的事情,我认为你必须创建一个真实的动物而不是模拟动物。

你可以要求输入你刚才插入的特定类型。你必须创建一个助手函数:

T Get<T>(T parameterOnlyToInferTheType)
{
    IList<Animal> animals= zoo.GetAnimalsOfType<T>();  
    return animals[0];
}

animal = MockRepository.GenerateStub<Animal>();
zoo.AddAnimal(animal);  
Animal expected = Get(animal);
Assert.That(expected, Is.EqualTo(animal)); 
T Get(T参数仅用于推断类型)
{
IList animals=zoo.GetAnimalsOfType();
返回动物[0];
}
animal=MockRepository.generateSub();
动物园.动物(动物);
预期动物=获得(动物);
断言。那(预期的,是。相等的(动物));
看起来还是有点不可靠,但应该可以用


一般来说,我倾向于避免对类型上的集合设置键控,因此我没有这些问题(例如,我在类上有一个返回枚举的属性等)。

实际上,您的第一个建议不起作用,因为编译器必须在执行前知道我在
zoo.GetAnimalsOfType()中请求的类型
并使用
zoo.GetAnimalsOfType()
事先无法知道该类型。然后我认为您必须使用真实的动物或滚动您自己的模拟并使用该类型。我将编辑答案。
Assert.That(animals[0], Is.SameAs(animal));
class Tiger : Animal
{
}

zoo.AddAnimal(new Tiger());  
IList<Animal> animals= zoo.GetAnimalsOfType<Animal>();
Assert.AreEqual(1, animals.Count);
T Get<T>(T parameterOnlyToInferTheType)
{
    IList<Animal> animals= zoo.GetAnimalsOfType<T>();  
    return animals[0];
}

animal = MockRepository.GenerateStub<Animal>();
zoo.AddAnimal(animal);  
Animal expected = Get(animal);
Assert.That(expected, Is.EqualTo(animal));