给定一个如下所示的类层次结构:
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 时保留“实例化”的真实车辆?