我想知道如何使用Groovy / Spock在类中模拟一些私有变量。 假设我们有这个代码:
public class Car {
private Engine engine;
public void drive(){
System.out.println("test");
if (engine.isState()) {
// Do something
} else {
// Do something
}
}
}
在Mockito,我可以写:
@Mock
private Engine engine;
@InjectMocks
private Car car = new Car();
@Test
public void drive() {
when(engine.isState()).thenReturn(true);
car.drive();
}
但我不知道如何在Spock中做同样的事情。什么是Spock中@InjectMocks
的等价物?
答案 0 :(得分:0)
这更像是一个Groovy而不是一个Spock问题。在Groovy中,您只需调用一个命名私有成员的构造函数,然后注入它。但这很难看,你应该通过依赖注入来重构可测试性,正如Tim Yates已经说过的那样。但是对于它的价值,这里是你可以(但不应该)这样做的方式:
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
是因为您的方法返回void
,我不知道您要检查哪些其他内容。
测试为绿色,控制台日志如下所示:
driving
false state
driving
true state
答案 1 :(得分:0)
我建议在制造Engine
时将其放入汽车中
public class Car {
private final Engine engine;
public Car(final Engine engine) {
this.engine = engine
}
// ...
}
然后,您可以使用JUnit像这样在示例中模拟引擎:
@Mock
private Engine engine;
private Car car = new Car(engine);
@Test
public void drive() {
when(engine.isState()).thenReturn(true);
car.drive();
}
或使用Spock:
private Engine engine = Mock();
private Car car = new Car(engine);
def "test drive"() {
given:
engine.isState() >> true
expect:
car.drive();
}