drl drl - 1 year ago 75
C# Question

Correct way to unit test the type of an object

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

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


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?

Lee Lee
Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download