AssignableTo Constraint
AssignableToConstraint tests that the actual value can be assigned to a variable of the specified type. In other
words, the actual value's type derives from or implements the expected type.
Usage
Is.AssignableTo(Type expectedType)
Is.AssignableTo<T>()
Examples
[Test]
public void AssignableToConstraint_Examples()
{
// A string can be assigned to object (string derives from object)
Assert.That("Hello", Is.AssignableTo(typeof(object)));
Assert.That("Hello", Is.AssignableTo<object>());
// A string can be assigned to IEnumerable<char>
Assert.That("Hello", Is.AssignableTo<IEnumerable<char>>());
// A List<int> can be assigned to IList<int>
Assert.That(new List<int>(), Is.AssignableTo<IList<int>>());
Assert.That(new List<int>(), Is.AssignableTo<IEnumerable<int>>());
// Negative: an int cannot be assigned to string
Assert.That(5, Is.Not.AssignableTo(typeof(string)));
}
Notes
Is.AssignableTo<T>()is true whentypeof(T).IsAssignableFrom(actual.GetType()).- This tests "can this value be assigned to a variable of type T?".
- This is the reverse of AssignableFromConstraint.
See Also
- AssignableFrom Constraint - Reverse direction check
- InstanceOfType Constraint - Test if object is instance of type
- ExactType Constraint - Test for exact type match