This is more a Groovy than a Spock question. In Groovy you can just call a constructor naming the private member and thus inject it. But this is ugly, you should rather refactor for testability via dependency injection as Tim Yates already said. But for what it is worth, here is how you can (but shouldn't) do it:
package de.scrum_master.stackoverflow;
public class Engine {
private boolean state;
public boolean isState() {
return state;
}
}
package de.scrum_master.stackoverflow;
public class Car {
private Engine engine;
public void drive(){
System.out.println("driving");
if(engine.isState()) {
System.out.println("true state");
} else {
System.out.println("false state");
}
}
}
package de.scrum_master.stackoverflow
import spock.lang.Specification
class CarTest extends Specification {
def "Default engine state"() {
given:
def engine = Mock(Engine)
def car = new Car(engine: engine)
when:
car.drive()
then:
true
}
def "Changed engine state"() {
given:
def engine = Mock(Engine) {
isState() >> true
}
def car = new Car(engine: engine)
when:
car.drive()
then:
true
}
}
BTW, then: true
is because your method returns void
and I don't know which other things you want to check.
The test is green and the console log looks like this:
driving
false state
driving
true state