'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?
Solution 1:[1]
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:
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jonas Nyrup |
| Solution 2 | avdeveloper |
