Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of currently running test in spock?

Tags:

spock

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.

like image 373
Noel Yap Avatar asked Dec 03 '11 04:12

Noel Yap


People also ask

What is stubbing in Spock?

Stubs are fake classes that come with preprogrammed return values. Mocks are fake classes that we can examine after a test has finished and see which methods were run or not. Spock makes a clear distinction between the two as mocks and stubs , as we will see in the sections to follow.

Why Spock framework?

Spock is a testing and specification framework for Java and Groovy applications. What makes it stand out from the crowd is its beautiful and highly expressive specification language. Thanks to its JUnit runner, Spock is compatible with most IDEs, build tools, and continuous integration servers.

What is Spock Lang specification?

lang. Specification class. A Spock specification can have instance fields, fixture methods, feature methods, and helper methods. We should prefer normal instance fields because they help us to isolate feature methods from each other.


2 Answers

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.

like image 180
Peter Niederwieser Avatar answered Oct 05 '22 10:10

Peter Niederwieser


For spock 1.0-groovy-2.4 you can try :

def "Simple test"() {

    expect:
    specificationContext.currentIteration.name == "Simple test"
}
like image 41
yu ki chan Avatar answered Oct 05 '22 09:10

yu ki chan