Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the unit test method name at runtime from within the unit test?

How to get the unit test name from the within unit test?

I have the below method inside a BaseTestFixture Class:

public string GetCallerMethodName() {     var stackTrace = new StackTrace();     StackFrame stackFrame = stackTrace.GetFrame(1);     MethodBase methodBase = stackFrame.GetMethod();     return methodBase.Name; } 

My Test Fixture class inherits from the base one:

[TestFixture] public class WhenRegisteringUser : BaseTestFixture { } 

and I have the below system test:

[Test] public void ShouldRegisterThenVerifyEmailThenSignInSuccessfully_WithValidUsersAndSites() {     string testMethodName = this.GetCallerMethodName();     // } 

When I run this from within the Visual Studio, it returns my test method name as expected.

When this runs by TeamCity, instead _InvokeMethodFast() is returned which seems to be a method that TeamCity generates at runtime for its own use.

So how could I get the test method name at runtime?

like image 712
The Light Avatar asked Mar 12 '12 11:03

The Light


People also ask

How do I get the method name in JUnit?

JUnit 4.9. @Rule public TestRule watcher = new TestWatcher() { protected void starting(Description description) { System. out. println("Starting test: " + description. getMethodName()); } };

How do you find the current test method name?

You can just use testResult. getMethod(). getMethodName().

Why is how you name a unit test and the variables within that test important?

A unit test method name is the first thing, anyone, trying to understand your code will read. It is important to write descriptive method names that help readers quickly identify the purpose of a test case. These method names communicate what the code does. A name should be concise, unambiguous, and consistent.

How do we define unit test within a test file?

Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. This testing methodology is done during the development process by the software developers and sometimes QA staff.


1 Answers

If you are using NUnit 2.5.7 / 2.6 you can use the TestContext class:

[Test] public void ShouldRegisterThenVerifyEmailThenSignInSuccessfully() {     string testMethodName = TestContext.CurrentContext.Test.Name; } 
like image 190
nemesv Avatar answered Sep 21 '22 06:09

nemesv