斯波克模拟私有变量



我想知道如何在与Groovy/Spock的类中模拟一些私有变量。假设我们有以下代码:

public class Car {
    private Engine engine;
    public void drive(){
        System.out.println("test");
        if (engine.isState()) {
            // Do something
        } else {
           // Do something
        }
    }
}

在莫克托中,我可以写:

@Mock
private Engine engine;
@InjectMocks
private Car car = new Car();
@Test
public void drive() {
    when(engine.isState()).thenReturn(true);
    car.drive();
}

但我不知道如何在斯波克做同样的事情。斯波克的@InjectMocks相当于什么?

这与其说是一个斯波克问题,不如说是一个Groovy问题。在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
  }
}

顺便说一句,then: true是因为您的方法返回void,我不知道您要检查哪些其他内容。

测试为绿色,控制台日志如下所示:

driving
false state
driving
true state

我建议在构造汽车时将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();
}

或者使用斯波克:

private Engine engine = Mock();
private Car car = new Car(engine);
def "test drive"() {
    given:
    engine.isState() >> true
    expect:
    car.drive();
}

相关内容

  • 没有找到相关文章

最新更新