Search code examples
c#fluent-assertions

FluentAssertions BeOfType<> failing with RuntimeType


I'm using reflection to get a custom attribute, and then I want to validate the type passed into the constructor, so I tried this:

var autoMapAttribute = dtoType.GetCustomAttribute<AutoMapAttribute>();

autoMapAttribute?.SourceType.Should()
    BeOfType<IbiSiliconProductStepping>();

It fails saying the type is System.RuntimeType. If I instead change the check to:

Be(typeof(IbiSiliconProductStepping));

then it succeeds. I'm confused why the first one doesn't work.


Solution

  • BeOfType is documented as:

    Asserts that the object is of the specified type T

    Where T is:

    The expected type of the object.

    Hence it checks that the asserted object is of type T (basically it checks that Subject is T type).

    This check would work if for example SourceType have stored something like the following (should not actually compile, just for example):

    IbiSiliconProductStepping something = ...;
    autoMapAttribute?.SourceType = something;
    

    In your case object you are asserting is the one stored in autoMapAttribute?.SourceType which is an instance of internal RuntimeType type (which inherits from the Type), which is kind of expected based on the name.

    The second one works because type stored in the SourceType is typeof(IbiSiliconProductStepping).