FluentAssertions Type check

xeraphim picture xeraphim · Oct 28, 2015 · Viewed 7.1k times · Source

I try to use FluentAssertions to check in my UnitTest, that the type of a property in a list of items is of a certain type.

myObj.Items.OfType<TypeA>().Single()
            .MyProperty1.GetType()
                .Should().BeOfType<TypeB>();

Unfortunately, my test fails with the following error message:

Expected type to be TypeB, but found System.RuntimeType.

Why does it say, that it found System.RuntimeType? I used the debugger to verify, that MyProperty1is of type TypeB and it is... am I using .BeOfType<> wrong?

Answer

ntohl picture ntohl · Oct 28, 2015

Please skip the .GetType(). You are asking not the MyProperty1's type, but the type's type. It's 1 level too deep.

public class TypeB { }

public class TypeA
{
    public TypeB MyProperty1 { get; set; }

    public TypeA()
    {
        MyProperty1 = new TypeB();
    }
}

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        List<object> objects = new List<object>();
        objects.Add("alma");
        objects.Add(new TypeA());
        objects.OfType<TypeA>().Single().MyProperty1.Should().BeOfType<TypeB>();
    }
}