Gargoyle
Gargoyle

Reputation: 10375

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.

Upvotes: 1

Views: 84

Answers (2)

Guru Stron
Guru Stron

Reputation: 143483

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).

Upvotes: 0

Ivan Petrov
Ivan Petrov

Reputation: 5100

SourceType returns an instance of type Type. In our case the derived from Type RuntimeType.

The instance represents the type IbiSiliconProductStepping but is not of the type IbiSiliconProductStepping.

Maybe this example would help visualize what you are trying to do:

Type stringTypeInstance = typeof(string); // returns System.RuntimeType
stringTypeInstance.Should().BeOfType<string>(); 
// AssertionFailedException: Expected type to be System.String, but found System.RuntimeType.

Upvotes: 2

Related Questions