How to get name of currently running test in spock?
Asked Answered
C

2

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.

Carpel answered 3/12, 2011 at 4:16 Comment(0)
S
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.

Schoolbag answered 3/12, 2011 at 4:38 Comment(2)
thanks it worked for me where we have special requirementTimely
is there some way to get the name from the script set-up def setup and after def cleanup?Luff
A
17

For spock 1.0-groovy-2.4 you can try :

def "Simple test"() {

    expect:
    specificationContext.currentIteration.name == "Simple test"
}
Arkose answered 11/5, 2017 at 5:28 Comment(1)
Better yet: specificationContext.currentIteration.displayNameDelisadelisle

© 2022 - 2024 — McMap. All rights reserved.