pixel
pixel

Reputation: 26483

Is there an option to generate dynamically n tests in Spock

I have a file with n lines.

In my Spock test, I download, read the file, and assert each line of it.

Is there a way to produce n tests in the report instead of a one?

Upvotes: 0

Views: 192

Answers (1)

kriegaex
kriegaex

Reputation: 67417

Maybe you know how to @Unroll Spock tests and feature method names like this:

package de.scrum_master.stackoverflow.q63002164

import spock.lang.Specification
import spock.lang.Unroll

class FixedInputBasedParametrisedTest extends Specification {
  @Unroll
  def "verify #inputLine"() {
    expect:
    inputLine.contains("et")

    where:
    inputLine << ["weather", "whether", "getters & setters"]
  }
}

The result when running the test e.g. in IntelliJ IDEA looks like this:

unrolled methods using fixed input data

But you can also use dynamic data providers, not just fixed sets of values. They just need to be Iterable.

If for example you have a resource file like this

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem
ipsum dolor sit amet.

you can use it as a data provider like this:

package de.scrum_master.stackoverflow.q63002164

import spock.lang.Specification
import spock.lang.Unroll

class InputFileBasedParametrisedTest extends Specification {
  @Unroll
  def "verify #inputLine"() {
    expect:
    inputLine.contains("et")

    where:
    inputLine << new File("src/test/resources/test.txt").readLines()
  }
}

The result will look like this:

unrolled methods using dynamic input data

Upvotes: 3

Related Questions