Correct way to unit test the type of an object
Asked Answered
R

6

34

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?

Roxyroy answered 12/3, 2014 at 20:6 Comment(0)
H
47

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
Hospitaler answered 12/3, 2014 at 20:9 Comment(0)
C
13

looks XUnit is better:

Assert.IsType<MyClass>(myObj);
Culvert answered 25/4, 2018 at 21:3 Comment(0)
A
11

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

Archaean answered 13/8, 2016 at 13:49 Comment(0)
G
7

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

Gospel answered 8/6, 2020 at 12:27 Comment(0)
I
4

In my case it works fine with next line:

Assert.IsAssignableFrom<TheClass>(result);
Ingham answered 21/2, 2019 at 13:38 Comment(0)
F
0

xUnit

Assert.True(result.GetType() == typeof(MyClassType));

enter image description here

Works pretty well.

Funerary answered 24/5, 2024 at 7:29 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.