To be clear, the specific problem you are encountering is that C# dynamic does not work with non-public members. This is by design, presumably to discourage that sort of thing. Since as LukLed stated, anonymous types are public only within the same assembly (or to be more precise, anonymous types are simply marked internal
, not public
), you are running into this barrier.
Probably the cleanest solution would be for you to use InternalsVisibleTo
. It allows you to name another assembly that can access its non-public members. Using it for tests is one of the primary reasons for its existance. In your example, you would place in your primary project's AssemblyInfo.cs the following line:
[assembly: InternalsVisibleTo("AssemblyNameOfYourTestProject")]
Once you do that, the error will go away (I just tried it myself).
Alternatively, you could have just used brute force reflection:
Assert.AreEqual(123, jsonResult.GetType().GetProperty("Id").GetValue(jsonResult, null));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…