Scott
Scott

Reputation: 2193

Assert Types .NET

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

Answers (4)

Jon Skeet
Jon Skeet

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

Yann Trevin
Yann Trevin

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

McKay
McKay

Reputation: 12614

Assert.IsTrue(variable is bool, "variable was not a Boolean Value");

Upvotes: 0

Matthew Vines
Matthew Vines

Reputation: 27581

if(myValue is Boolean)
{

}

Upvotes: 1

Related Questions