简体   繁体   English

如何对RuntimeType进行单元测试

[英]How to Unit Testing RuntimeType

[Test]
// arrange 
// ...
// act
var result = (Car) service.GetCar(req);

// assert
Assert.AreEqual(result, typeof(Car));  

But I'm getting following error 但我收到以下错误

Expected: <Models.Car> (Car)    
But was:  <Models.Car> (RuntimeType)

I tried to change assert to use Is.InstanceOf : 我试图更改断言以使用Is.InstanceOf

Assert.AreEqual(result, Is.InstanceOf<Car>());

But I'm still getting error, this time 但是这次我还是出错

Expected: <Models.Car>
But was:  <<instanceof Models.Car>>

You don't need to cast the result of service.GetCar(req) . 您无需service.GetCar(req)的结果。 This would work: 这将工作:

var result = service.GetCar(req);

Assert.IsInstanceOf<Car>(result);

Or, as an alternative, use: 或者,作为替代,使用:

var result = service.GetCar(req);

Assert.That(result, Is.TypeOf<Car>());

Following means that you want to compare object and type, while you want to compare type of the object: Assert.AreEqual(result, typeof(Car)); 以下表示您要比较对象和类型,而要比较对象的类型: Assert.AreEqual(result, typeof(Car));

You could use: Assert.AreEqual(result.GetType(), typeof(Car)); 您可以使用: Assert.AreEqual(result.GetType(), typeof(Car)); , but I'm not sure if this will work. ,但我不确定这是否行得通。

But the best option is to try casting and failing if cast is not successfull: 但是最好的选择是尝试转换,如果转换失败,则失败:

try
{
    var result = (Car) service.GetCar(req);
}
catch (Exception ex)
{
    Assert.Fail();
}

or you could use Assert.ThrowsException() method to check if exception been thrown, but it's not straightforwards, as previous method. 或者,您可以使用Assert.ThrowsException()方法检查是否抛出了异常,但与以前的方法一样,它并不简单。

Action action = () => { var result = (Car) service.GetCar(req); };
Assert.ThrowsException<Exception>(action);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM