문제

Using the Visual Studio Unit Testing Framework, I'm looking at two options:

Assert.AreEqual(myObject.GetType(), typeof(MyObject));

and

Assert.IsInstanceOfType(myObject, typeof(MyObject));

Is there a difference between these two options? Is one more "correct" than the other?

What is the standard way of doing this?

도움이 되었습니까?

해결책

The first example will fail if the types are not exactly the same while the second will only fail if myObject is not assignable to the given type e.g.

public class MySubObject : MyObject { ... }
var obj = new MySubObject();

Assert.AreEqual(obj.GetType(), typeof(MyObject));   //fails
Assert.IsInstanceOfType(obj, typeof(MyObject));     //passes

다른 팁

Minor syntactical point: while the above Assert.AreEqual() statements will work, the order of the parameters should be reversed, i.e., Assert.AreEqual(Type expected, Type actual).

So, in this case: Assert.AreEqual(typeof(MyObject), obj.GetType());

looks XUnit is better:

Assert.IsType<MyClass>(myObj);

In NUnit

Assert.That(myObject, Is.TypeOf<MyObject>()) //Tests exact type

and

Assert.That(myObject, Is.InstanceOf<MyObject>()) //Tests type and subtype

Easiest asserts to understand because of naming that NUnit followed :)

In my case it works fine with next line:

Assert.IsAssignableFrom<TheClass>(result);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top