Reputation: 2105
I am writing my own poor-man's testing framework. In my console application, I have this:
static void Main(string[] args)
{ // Line 12
double adouble = 77;
double expected = 70;
TestingFramework.assertEquals<double>(expected, adouble - 7); // Line 15
TestingFramework.assertEquals<double>(expected, adouble - 6); // Line 16
}
Within TestingFramework I have this line:
System.Console.WriteLine("Success, File {0}, Line {1}",
new System.Diagnostics.StackTrace(true).GetFrame(1).GetFileName(),
new System.Diagnostics.StackTrace(true).GetFrame(1).GetFileLineNumber());
But when I run the test, it tells me that FileLineNumber is 12 for both function calls. Further, it gives me the correct file name, so I am think it is referencing the correct frame.
Can someone tell me how I can get it to report to me the line number that originated the call (15 then 16), and not the line number of the open paren (12)?
Thanks.
Upvotes: 2
Views: 2937
Reputation: 2105
I have figured out the problem and how to fix it.
I had overloaded the assertequals function in TestingFramework: 1) assertEquals(T expectedValue, T actualValue) and 2) assertEquals(T expectedValue, T actualValue, string comment).
When client code calls the 2-param function, that function just calls the 3-param function. This different frame depths depending on how it was called.
So I had to add
static int depth;
which I increment when entering a function and decrement when exiting. This changes the code to:
new System.Diagnostics.StackTrace(true).GetFrame(depth).GetFileLineNumber());
and that now works.
Upvotes: 0
Reputation: 10424
Appending to my comment, something like this:
foreach(var frame in StackTrace.GetFrames())
{
System.Reflection.MethodBase method = frame.GetMethod ( );
Type type = method.DeclaringType;
// If this is what I am looking for
if ( type.IsSubclassOf( typeof(TestClassBase)) || type != typeof ( TestClassBase) )
{
System.Console.WriteLine("Success, File {0}, Line {1}", frame.GetFileName(), frame.GetFileLineNumber());
return;
}
}
Upvotes: 1