Simple `Assert.IsAssignableFrom <T>` crash
Why does this simple statement statement fail? From what I read, it should be. Unfortunately, since the functionality is so basic, there is not much information.
public interface IDummy{} public class Dummy : IDummy {} Assert.IsAssignableFrom<IDummy>(new Dummy()); Performing this test gives
Expected: assignable from <Application.Tests.ViewModels.IDummy> But was: <Application.Tests.ViewModels.Dummy> I tried to replace the interface and some of the objects to no avail.
IsAssignableFrom works in the opposite direction from what you expect. He asks: Is (value) Assignable From IDummy. Or: "Assigned (value)?"
From an XML document: /// Claims that an object can be assigned a value of this type.
You probably need Assert.IsInstanceOfType ()
In the interest of those who land here via Google (or Bing :-))
Assert.IsAssignableFrom<T>(object actual) intended to check whether the test object can be replaced by type T. Effectively this means that this statement checks the "is-a" relationship between the object and type T.
Let's look at some code (intentionally simplified):
// The Base class public class Employee { public int EmployeeId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime DateOfJoining { get; set; } } // The derived class public class Manager : Employee { public IList<Employee> EmployeesReporting { get; set; } } Now the statement:
// NOTE: using Assert = NUnit.Framework.Assert; [TestMethod] public void Test_IsAssignableFrom() { var employee = new Employee(); // Manager is-a Employee, so the below is true Assert.IsAssignableFrom<Manager>(employee); } While IsInstanceOf<T>(object actual) intended to check whether the test object (for example, the name) is an instance of type T - just put it if the "actual" is a type T or a type derived from T
[TestMethod] public void Test_IsAssignableFrom() { var manager = new Manager(); // Manager derives from Employee so the below is true Assert.IsInstanceOf<Employee>(manager); } EDIT It turns out that these statements work the same as the Type.IsAssignableFrom and Type.IsInstanceOf methods on System.Type