5

给定一个如下所示的类层次结构:

public class Vehicle {

    private String name;

    public Vehicle(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

}


public class Car extends Vehicle {

    public Car(String name) {
        super(name);
    }

    public String drive() {
        return "driving the car";
    }

    public String boardBus() {
        Bus bus = new Bus("bus to cut off");

        return bus.board();
    }

}

public class Bus extends Vehicle {

    public Bus(String name) {
        super(name);
    }

    public String board() {
        return "boarding the bus";
    }

}

我正在尝试测试 Car 类。但是,Car 也恰好使用 Bus。所以,在我的测试中,我试图模拟 Bus。我的测试代码如下所示:

import static org.junit.Assert.assertEquals;
import mockit.Mocked;
import mockit.NonStrictExpectations;

import org.junit.Test;

public class CarTest {

    @Test
    public void testCar() {
        final String name = "I am a car";
        final Car car = new Car(name);

        new NonStrictExpectations() {
            @Mocked Bus bus;

            {
                bus.board(); result = "test bus boarding";
            }
        };

        assertEquals("I am a car", car.getName());
    }

}

断言失败,因为car.getName()返回 null。

通过在 Vehicle、Car 和 Bus 的构造函数中插入System.out.println's,我怀疑加载的“真实”Vehiclenew Car(name)稍后会在执行时被模拟的 Vehicle 替换@Mocked Bus bus

jmockit 有没有办法在构建 Car 时保留“实例化”的真实车辆?

4

2 回答 2

1

我看到两个解决方案:

@Test
public void boardBus_usingInstanceSpecificMockingForNewedInstances()
{
    new Expectations() {
        @Capturing @Injectable Bus bus;

        {
            bus.board(); result = "mocked";
        }
    };

    String result = new Car("myCar").boardBus();
    assertEquals("mocked", result);
}

@Test
public void boardBus_usingPartialMocking()
{
    final Bus bus = new Bus("");
    new Expectations(bus) {{ bus.board(); result = "mocked"; }};

    String result = new Car("myCar").boardBus();
    assertEquals("mocked", result);
}
于 2011-07-20T19:42:55.720 回答
0

没有与汽车“关联”的车辆 - 汽车车辆。关联和继承是不一样的。因此,不可能有一辆带有“模拟”车辆的汽车——这句话在Car extends Vehicle.

您确定 Car 的构造函数中没有(合法的)错误getName()吗?这些方法的代码是什么样的?

于 2011-07-20T15:05:49.980 回答