How to access the NUnit test name programmatically?

TALlama picture TALlama · Aug 28, 2010 · Viewed 17.5k times · Source

Is there some global state somewhere that I can access the currently-running test name?

I have tests which output files into a directory and read them back in. I'd like each test to create a directory to play in and then clean up after itself, and I don't want to push that name in (I'd have to make it unique, and then make sure each test keeps it unique; ew). I could use a GUID, but I'd like helper methods to be able to assume "this is the place where test files should be stored" without having to push that GUID around to them. Again, this augers for a global state somewhere.

Basically, I want a call like TestRunner.Current.CurrentTest.Name. Does such a thing exist?

Answer

Izzy picture Izzy · Jan 15, 2013

(Assuming c#)

NUnit.Framework.TestContext.CurrentContext.Test.Name 

or

NUnit.Framework.TestContext.CurrentContext.Test.FullName

or if you are really lazy and aren't driving your tests with TestCaseSource (thanks @aolszowka):

this.GetType().ToString()