Reputation: 115
We use our "own" assert methods which allow to pass a message but do not force it. Most of our code base use the "without message" one... Which is problematic when you have more than one assert and the code changes between the bug reporting and the bug fixing...
I would like to print, in the assert message, the caller line in plain text. Something like:
int toto = 1;
SomObject obj = null;
Assert(toto == 0);
Assert(obj);
Assert(toto == 0, "some useful info");
Expected output:
Assertion failed. Parameter='toto == 0'
Assertion failed. Parameter='obj'
Assertion failed. 'some useful info'
We found this thread talking about Cecil Mono.Cecil - simple example how to get method body ...
It could be a way to go, but would means we have to rebuild the line based on the ILCode. Is there a way to get the "plain text code" in an other way?
[EDIT] We are running on C# 8.
Upvotes: 0
Views: 553
Reputation: 4666
You can try CallerArgumentExpressionAttribute
(https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute?view=net-6.0) to get actual assert expression/condition and show it as a message.
public static void Assert(bool condition,
[CallerArgumentExpression("condition")] string message = null)
{
//code here
}
Usage
// message argument in Assert will be "result==true" (as string)
Assert(result==true);
// message argument in Assert will be "Custom message"
Assert(result==true, "Custom message");
Upvotes: 7