How do you mock a Sealed class?

前端 未结 10 2331
鱼传尺愫
鱼传尺愫 2020-11-27 15:27

Mocking sealed classes can be quite a pain. I currently favor an Adapter pattern to handle this, but something about just keeps feels weird.

So, What is t

10条回答
  •  被撕碎了的回忆
    2020-11-27 15:41

    I came across this problem recently and after reading / searching web, seems like there is no easy way around except to use another tool as mentioned above. Or crude of handling things as I did:

    • Create instance of sealed class without getting constructor called.
    • System.Runtime.Serialization.FormatterServices.GetUninitializedObject(instanceType);

    • Assign values to your properties / fields via reflection

    • YourObject.GetType().GetProperty("PropertyName").SetValue(dto, newValue, null);
    • YourObject.GetType().GetField("FieldName").SetValue(dto, newValue);

提交回复
热议问题