Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 825
Scott Avatar asked Nov 09 '10 20:11

Scott


People also ask

What is the Assert class in C#?

In a debug compilation, Assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

What is Assert single?

xUnit has an Assert. Single (IEnumerable<T>) and Assert. Single (IEnumerable) that each test for the existence of a single element, and throw an exception if not, but return the single element if there is one.

How do you compare two objects in Assert?

In order to change the way two objects are compared in an assert we only need change the behavior of one of them – the expect value (might change depending on the unit testing framework).

How do you Assert equal?

Definition and UsageThe assert. equal() method tests if two values are equal, using the == operator. If the two values are not equal, an assertion failure is being caused, and the program is terminated. To compare the values using the === operator, use the assert.


1 Answers

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

like image 147
Jon Skeet Avatar answered Sep 25 '22 00:09

Jon Skeet