0

I have the following function that should output the class name of the calling class. Handily I have tested it and it works, it returns the calling class name.

public static string ExtractCallingClassName() {
  using System.Diagnostics;
  // Get call stack
  StackTrace stackTrace = new StackTrace(); 
  // Get calling method name
  return stackTrace.GetFrame(2).GetMethod().DeclaringType.Name;
}

However, the unit test returns RuntimeMethodHandle instead of the test class name.

[Fact]
public void ExtractCallingClassNameShouldExtractCorrect() {
      string expectedName = this.GetType().Name;
      string actualName = AssemblyExtractor.ExtractCallingClassName();
      Assert.Equal(expectedName, actualName);
}

Output:

Assert.Equal() Failure
          ↓ (pos 0)
Expected: AssemblyExtractorTest
Actual:   RuntimeMethodHandle
          ↑ (pos 0)

The test is in another project. The source project is linked in the test project as project reference.

Does anyone know why the test fails?

The source project is a class library. Will it work if I include it as package reference?

DaveVentura
  • 612
  • 5
  • 19
  • 2
    Take a look at this https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method – satnhak Feb 10 '22 at 17:11
  • 1
    I also think you might reinventing the wheel. See CallerMemberName .... – Mat Feb 10 '22 at 17:29

0 Answers0