Question

I have Spock Helper method in a particular Spec. This method generates strings to test sized constraints:

def genString(size) {
    def nameTooLong = 'x'
    size.times { nameTooLong <<=  "x" }
    return nameTooLong
}

I would like to re-use this helper method in other Specs as well. How to do it?

Thank you for helping

p.s. is there groovy kung-fu to accomplish the same thing in single short line, so I can pass as argument when initializing instances?

Was it helpful?

Solution

You could also change your function to:

def genString(size) {
  'x' * ( size + 1 )
}

or

def genString(size) {
  'x'.padLeft( size + 1, 'x' )
}

This second one, you could probably inline into your tests as it's pretty self-contained

OTHER TIPS

You could also use inheritance.

class SharedFixture extends Specification {
    def sharedMethod() {
       ......
    }
}

Then

class TestClass extends SharedFixture {
    def test() {
       sharedMethod()
    }
}

I had a similar need for Spock Tests and re-using helper methods across Specifications that generate Test data.

These helper methods started in one Spec.

I just refactored and created a helper class with static methods.

You could do the same, create a helper class and move in your test method as such:

class TestDataGen {

    ....
    public static String genString(size) {
        def nameTooLong = 'x'
        size.times { nameTooLong <<=  "x" }
        return nameTooLong
    }
    ....
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top