Search code examples
unit-testingocunit

Test name in the setUp/tearDown methods


SetUp and tearDown methods are called on every test. Is it possible to know the current (running) test name in the setUp and tearDown methods? I need to do some extra work depending on what is the currently running test.


Solution

  • You can use the selector method in your SenTestCase subclass to get the SEL of the test method that is is going to be executed(in setUp) / was executed(tearDown). Then you can use NSStringFromSelector to convert the SEL to a string.

    Here an example:

    NSString *testToExecute = NSStringFromSelector([self selector]);
    

    However I would rethink the way you are writing your test. I don't like the idea of executing conditional code in setUp depending on what test is going to run... To solve that you better extract that conditional code to a method and call that method from all test methods you want. Or you could even create a separate test class for those test cases, doing that extra work in its setUp/tearDown for all its test methods.