这是我试图实现的结果的略微简化版本,但我认为它说明了问题。
想象一下,我有以下两个类,其中一个是另一个的后代:
<h1>The story began.</h1>
<em><strong>This would</strong></em> be an example of a post that I'm trying to reformat via better HTML.
<a href="http://mobiscreenr.com/wp-content/uploads/2015/05/note.jpg"><img class="aligncenter size-full wp-image-100" src="http://mobiscreenr.com/wp-content/uploads/2015/05/note.jpg" alt="note" width="119" height="163" /></a>
我也有这个测试代码:
public class Vehicle {
protected String name;
{
name = "Vehicle";
}
public String getName() {
return name;
}
}
public class Car extends Vehicle {
{
name = "Car";
}
}
我想要在控制台输出上看到的是:
Starting a mocked vehicle Starting a mocked car
但是,实际输出如下所示:
Starting a mocked car Starting a mocked car
我是JMockit的新手所以我想想我知道为什么会发生这种情况(因为JMockit会在类层次结构中一直模拟模拟的所有祖先类) ,不包括public class VehiclesTest {
@Test
public void checkVehicles(@Mocked final Vehicle vehicleMock,
@Mocked final Car carMock) {
new Expectations() {
{
vehicleMock.getName(); result = "mocked vehicle";
carMock.getName(); result = "mocked car";
}
};
Vehicle aVehicle = new Vehicle();
System.out.println("Starting a " + aVehicle.getName());
Vehicle aCar = new Car();
System.out.println("Starting a " + aCar.getName());
}
}
)。
如何设定我的期望,以便获得我想要的结果?是否有可能在同一层次结构中对不同类别的多个模拟设置期望(即,哪一个是另一个的后代)?
答案 0 :(得分:1)
以下测试将起作用:
@Test
public void checkVehicles(@Mocked Vehicle anyCarOrVehicle) {
new Expectations() {{
new Vehicle().getName(); result = "mocked vehicle";
new Car().getName(); result = "mocked car";
}};
assertEquals("mocked vehicle", new Vehicle().getName());
assertEquals("mocked car", new Car().getName());
}
当然,在这种情况下的API并不明显。如果可以的话,最好的事情就是尽量避免嘲笑。特别是,模拟意味着用于模拟和验证行为,而不是 state 。所以,如果你嘲笑“吸气剂”,这是一个糟糕的测试方法的强烈信号。