Tuesday, 24 July 2012

How to Use Assert.IsAssignableFrom in xUnit

Assert.IsAssignableFrom<{type}>({object}) method means whether {type} is assignable from the type of {object} which also means whether {object} has a type similar to or is derived from {type}. While Assert.IsType method is used to test an object against a particular type, Assert.IsAssignableFrom offers more flexibility.

Let us look at some examples of this. Say that we have these classes:
public class BaseClass{}
public class TestClass : BaseClass{}
public class DerivedClass : TestClass{}

Then when we write these unit tests below. The results are commented out on each test.
public class Test
{
    private TestClass testClass;

    public Test()
    {
        testClass = new TestClass();
    }

    [Fact]
    public void test1() //Pass
    {
        Assert.IsType<TestClass>(testClass);
    }

    [Fact]
    public void test2() //Pass
    {
        Assert.IsAssignableFrom<TestClass>(testClass);
    }

    [Fact]
    public void test3() //Pass
    {
        var result = Assert.IsAssignableFrom<BaseClass>(testClass);
        //Assert.IsType<BaseClass>(result); //failed
        Assert.IsType<TestClass>(result);
    }

    [Fact]
    public void test4() //Pass
    {
        var result = Assert.IsAssignableFrom<Object>(testClass);
        //Assert.IsType<Object>(result); //failed
        //Assert.IsType<BaseClass>(result); //failed
        Assert.IsType<TestClass>(result);
    }

    [Fact]
    public void test5() //Failed
    {
        Assert.IsAssignableFrom<DerivedClass>(testClass);
    }
}
Note that when using implicit type 'var' to hold the result of Assert.IsAssignableFrom method, the new variable's type is still the same as the tested object type (line 26 & 34).

No comments: