Reputation: 2193
Is there a way that you can assert whether or not a variable is of a certain type?
Such as:
AssertIsBoolean(variable);
Upvotes: 8
Views: 5396
Reputation: 1502656
Are you really trying to assert that a variable is of a particular type, or that the value of a variable is of a particular type?
The first shouldn't be part of a unit test - it's part of the declared code. It's like trying to unit test that you can't call a method with the wrong argument types.
The second can easily be accomplished with
Assert.IsTrue(value is bool);
(Assuming value
is a variable of type object
or an interface.)
Note that that will test for compatibility rather than the exact type. If you want to test that a value is an exact type, not a subtype, you might use something like:
Assert.AreEqual(typeof(ArgumentException), ex.GetType());
(There may be options available for generic methods in whatever unit test framework you use, of course.)
Upvotes: 10
Reputation: 3823
You don't specify which testing framework you use. So I would like to mention that the Gallio/MbUnit testing framework provides a convenient assertion for that very purpose:
Assert.IsInstanceOfType<bool>(myValue);
Upvotes: 0
Reputation: 12614
Assert.IsTrue(variable is bool, "variable was not a Boolean Value");
Upvotes: 0