20

In JUnit 3, I could get the name of the currently running test like this:

public class MyTest extends TestCase {
    public void testSomething() {
        assertThat(getName(), is("testSomething"));
    }
}

How do I do this in spock? I would like to use the test name as a key in a shared resource so that tests don't interfere with each other.

Noel Yap
  • 18,822
  • 21
  • 92
  • 144

2 Answers2

23

One solution is to leverage JUnit's TestName rule:

import org.junit.Rule
import org.junit.rules.TestName

class MySpec extends Specification {
    @Rule TestName name = new TestName()

    def "some test"() {
        expect: name.methodName == "some test"
    }
}

This requires JUnit 4.7 or higher.

Peter Niederwieser
  • 121,412
  • 21
  • 324
  • 259
17

For spock 1.0-groovy-2.4 you can try :

def "Simple test"() {

    expect:
    specificationContext.currentIteration.name == "Simple test"
}
yu ki chan
  • 171
  • 1
  • 2