Jonathan Chen
Jonathan Chen

Reputation: 716

Get name of test method in setUp (Xcode)

I want to append a message to a log that includes the name of the test method that is about to be run. I want to do this in my setUp method in my test superclass so I don't have repeated code everywhere.

I wanted to do something like this:

- (void) setUp {
    [super setUp];
    [self log:@NSStringFromSelector(_cmd)];
}

However, _cmd always gives "setUp" as its string, whereas I want "test00TestTheThing"

Is there a way to do this?

Upvotes: 4

Views: 4393

Answers (2)

nir barzilay
nir barzilay

Reputation: 91

Don't know if it's still relevant but if someone needs it:

you can use the self.name and then you'll get the name of the class with the name of the test.

To remove the class name and just stay with the test name, use the replacingOccurrences func

example:

class ClassName: XCTestCase {
    override func setUp() {
      // get the name and remove the class name and what comes before the class name
      var currentTestName = self.name.replacingOccurrences(of: "-[ClassName ", with: "")

      // And then you'll need to remove the closing square bracket at the end of the test name

      currentTestName = currentTestName.replacingOccurrences(of: "]", with: "")
    }

Upvotes: 3

Jonathan Chen
Jonathan Chen

Reputation: 716

I found this:

self.name

However, this gives me "-[AppUITests test00TestTheThing]"

Upvotes: 12

Related Questions