Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create helper method in spock test that will not be run as a test

I'm a java developer finding myself modifying a groovy test, so I apologize if I'm pretty ignorant about basic groovy concepts and terminology (I think I should be saying closure instead of method here?)

In any case, my desire is simple, I want to create some helper methods that can be reused within an existing groovy test. Things like starting/stopping resources that are only needed for certain tests (and would break others), or to preform a common testing step faster.

However, it seems that any time I try to create a method (closure?) like this it gets run by spock as a test, which breaks other tests in fun ways. Is there a simple way to add a method to my spock tests without it being run as a test?

It looks like making it static may work, but there are methods I want which would touch @shared variables of the class, so I'm not sure static is the best option.

like image 532
dsollen Avatar asked Jan 06 '23 03:01

dsollen


1 Answers

I've been using traits extensively to write unit tests.

Each trait introduces test functionality to a Specification.

trait Helper {
    def helpTests() {
        println "Starting Test"
        return 2
    }
}

class MySpec extends Specification
        implements Helper {
    def "my spec"() {
        when:
        def n = helpTests()

        then:
        n == 2
    }
}

The trait methods are not executed, obviously.

like image 175
Renato Avatar answered Apr 26 '23 19:04

Renato