Correct way to unit test the type of an object
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);
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