In C#, there is the Exception
class. For the purposes of testing, I would like to be able to set its StackTrace
property to arbitrary strings. StackTrace
has no setter, so my first attempt was to try using reflection:
Exception instance = new Exception("Testing");
PropertyInfo propertyInfo = typeof(Exception).GetProperty("StackTrace");
propertyInfo.SetValue(instance, "Sample StackTrace value", null);
This yields the runtime error:
System.ArgumentException : Property set method not found.
Is there any way I could set the StackTrace
property? More generally, is there a way to set a property that lacks a setter?
You could derive your own exception class and override the
StackTrace
property, which is virtual:Note that to do this properly, you should really implement all the standard exception constructors, but for unit testing this might not be strictly necessary.
See Designing Custom Exceptions for more details:
That property is implemented this way:
And that called method is implemented this way:
So it seems that if you set the field
_stackTraceString
to anyString
, you will get_stackTraceString
+_remoteStackTraceString
.You can set fields with FieldInfo.SetValue.
I got this information using http://ilspy.net.
Do not do this on production. Things are designed in a specific way for a reason, just the exposed API is guaranteed, a minor upgrade could change this internal implementation detail and break your code, so never rely on internal details, just exposed APIs.
Cheers.
You can modify the backing field of the object:
This should work, to get a list of private fields you can use:
Personally I prefer the solution proposed by Matthew Watson.
The StackTrace property of an Exception object is set by the runtime during stack walk, so we cannot set it manually.