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