avdeveloper
avdeveloper

Reputation: 549

Cannot read dynamic properties with FluentAssertions

I am using XUnit and fluentassertions in c sharp for my unit tests. Below is where I get a dynamic type, convert a dynamic object to that dynamic type and try to do an assertion:

        var dynamicType = Type.GetType(...);

        dynamic? myObject = JsonSerializer.Deserialize(myJSONData, dynamicType);

        myObject!.Products!.Should().NotBeNull();

If I debug it, myObject does have the required properties and values, however c sharp and fluentassertion throw this error:

  Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'xxxxx.Products' does not contain a definition for 'Should'

Is it possible to do the comparison or did I miss out anything?

Upvotes: 1

Views: 2063

Answers (2)

avdeveloper
avdeveloper

Reputation: 549

This is a simple way to do it, just add (object) cast in front of the assert if your object is dynamic.

(object) myObject!.Products!.Should().NotBeNull();

You need to import System.Object.

Upvotes: 2

Jonas Nyrup
Jonas Nyrup

Reputation: 2586

It's a limitation in .NET. It does not support extension methods for dynamic objects.

A workaround is to cast myObject into an object, such that the appropriate overload of Should can be determined at compile time.

Some related issues:

Upvotes: 6

Related Questions