问题描述
我想知道如何在Groovy/Spock的类中模拟一些私有变量.假设我们有以下代码:
I'm wondering how I can mock some private variable in a class with Groovy/Spock.Let's say we have this code:
public class Car {
private Engine engine;
public void drive(){
System.out.println("test");
if (engine.isState()) {
// Do something
} else {
// Do something
}
}
}
在Mockito中,我可以写:
In Mockito I can write:
@Mock
private Engine engine;
@InjectMocks
private Car car = new Car();
@Test
public void drive() {
when(engine.isState()).thenReturn(true);
car.drive();
}
但是我不知道如何在Spock中做同样的事情.Spock中的 @InjectMocks
等效于什么?
But I don't know how to do the same in Spock. What is the equivalent of @InjectMocks
in Spock?
推荐答案
与Spock问题相比,这更像是Groovy.在Groovy中,您可以调用一个构造函数来命名私有成员,然后注入它.但是,这很丑陋,您应该像蒂姆·耶茨(Tim Yates)所说的那样通过依赖注入重构可测性.但是,为了它的价值,这是您可以(但不应该)这样做的方法:
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
}
}
顺便说一句,然后:true
是因为您的方法返回了 void
,并且我不知道您要检查哪些其他内容.
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
这篇关于Spock模拟私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!