Question

Help me please to realize what wrong with me and my code. Simple example:

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);
}

}

All I need is to return real result of execution of mocked objects. I was trying to use delegate, simple result= option and returns() but all the time it returns 0, 0.00 when i expecting 4 and 55.3. I have tried to mock all dependencies one by one, mock upper level and so one... I do it just for learning so if it wrong conceptually please tell me. My current goal is to moke all dependencies and during execution return Cargo(4,55.3). Thank in advance.

Was it helpful?

Solution

It's not shown but I assume that class RollingStock defines method getChassisCount() and fields chassisCount and maxWeight.

Your mock is not working because you have mocked RollingStock at the start of your test: @Mocked RollingStock rollingStockMock;

Because of this when your test calls car.getChassisCount() you are calling a mocked method and you are getting the default return value for a method returning an int, which is 0. Removing this mocking enables your test to pass.

Note you have the Assert.equals parameters mixed up. The expected value should be the first parameter and the second should be the actual parameter. This will make failed test cases easier to understand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top