Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)); 

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?

like image 993
drl Avatar asked Mar 12 '14 20:03

drl


People also ask

Which of the following is correct about a unit test case?

Q 10 - Which of the following is correct about a Unit Test Case? A - A Unit Test Case is a part of code which ensures that the another part of code (method) works as expected.

What are the three steps in a unit test?

In the overall view of any unit test application, we will see that a unit test is a three-step processes. The first one is setup test or arrange test, Act test or execute unit test and Assert means verify test result with expected results.


2 Answers

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 
like image 58
Lee Avatar answered Sep 29 '22 16:09

Lee


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());

like image 24
Tim Peara Avatar answered Sep 29 '22 16:09

Tim Peara