Test data belongs in the where block, not hard coded in the test (feature) method.
One rough way to see this is to think of the test body (excluding the where block) as a method with some number of parameters -- 2 in your case, name and length. And then realize that the where clause just provides data values to the test runner to use when invoking your test method.
Spock uses Groovy magic to transform
def "test length of names"() {
expect:
name.size() == length
where:
name | length
"Spock" | 5
"Java" | 4
}
into something roughly like
def test_length_of_names(name, length) { // note the arguments
assert name.size() == length
}
and then tells the test runner to call the test once for each row in the where clause
test_length_of_names("Spock", 5)
test_length_of_names("Java", 4)
This approach
- provides a nice separation of concerns between test logic and test data
- allows relatively generic tests to be reused for a wide range of inputs and edge cases
- avoids duplication in test code
- supports a test design style that deserves the name data-driven testing.
This explanation leaves out a few details, such as creating an instance of the spec for each test, updating the name of each test invocation and calling the various setup and cleanup methods.
See the Spock documentation for more details.
Where
were an interface that allowed theprivate Where getTestData(){...}
to return a where table from Anuj's example. And of course I'd prefer to have the tidy table syntax. Thanks for the very clear explanation. – Prakrit