无法从模拟类型返回新Object

时间:2013-10-15 14:51:04

标签: mocking jmockit

请帮我理解我和我的代码有什么问题。 简单的例子:

public class RollingStockCreation {
@Mocked Plant plant;
@Mocked RollingStock rollingStockMock;
@Mocked WrenchManagerInjection wm;


@Test
public void rollingStockCreationWithTwoMocks(){

    new Expectations(){
        {
            wm.getCar();
            result = new Delegate() {
            Cargo delegate(){
                return new Cargo(4,55.3);
            }
        };
        }
    };
    Assert.assertEquals(wm.getCar().getChassisCount(),4);
}

}

public class Cargo extends RollingStock {
protected String cargoType;
public Cargo(int chassisCount, double maxWeight){
    this.chassisCount = chassisCount;
    this.maxWeight = maxWeight;
}

public String getCargoType() {
    return cargoType;
}

public void setCargoType(String cargoType) {
    this.cargoType = cargoType;
}

}

public abstract class Plant {
RollingStock rollingStock;
public RollingStock construct(RollingStock rollingStock){
    this.rollingStock = rollingStock;
    return rollingStock;
}

}

public class WrenchManagerInjection {
Plant plant;
RollingStock rollingStock;

@Inject
public WrenchManagerInjection(Plant plant, RollingStock rollingStock) {
    this.plant = plant;
    this.rollingStock = rollingStock;
}

public RollingStock getCar() {
    return plant.construct(rollingStock);
}

public static RollingStock getCar(Plant plant, RollingStock rollingStock) {
    return plant.construct(rollingStock);
}

}

我所需要的只是返回执行模拟对象的真实结果。我试图使用代表, simple result = option和returns()但是当我期望4和55.3时它总是返回0,0.00。我试图逐个模拟所有依赖项,模拟上层等等......我只是为了学习而这样做,如果它在概念上错了请告诉我。我目前的目标是终止所有依赖关系并在执行期间返回Cargo(4,55.3)。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

它没有显示,但我假设类Rollingche定义了方法getChassisCount()和fieldsCount和maxWeight字段。

你的模拟不起作用,因为你在测试开始时嘲笑了RollingStock: @Mocked RollingStock rollingStockMock;

因此,当您的测试调用car.getChassisCount()时,您正在调用一个模拟方法,并且您将获得返回int的方法的默认返回值,该值为0。 删除此模拟可以使您的测试通过。

请注意,Assert.equals参数已混淆。期望值应该是第一个参数,第二个参数应该是实际参数。这将使失败的测试用例更容易理解。