0

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?

avdeveloper
  • 449
  • 6
  • 30

2 Answers2

4

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:

Jonas Nyrup
  • 2,376
  • 18
  • 25
0

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.

avdeveloper
  • 449
  • 6
  • 30