当我使用Mockito.mock()模拟一个对象时,我希望该对象能够删除返回null,0,false等的方法,而不需要任何真实对象的代码。嘲讽。我认为这是Java中的默认行为,但Android似乎将真实对象作为模拟的一部分。我该如何避免这种情况?
public class MockTest extends InstrumentationTestCase {
public void testMock() {
Engine engine = mock(Engine.class);
Car car = new Car(engine);
car.start(); // Null pointer error, because Engine.starter is null.
verify(engine, Mockito.times(1)).engageStarter();
}
public static class Car {
private final Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
public void start() {
engine.engageStarter();
}
}
public static class Engine {
private final Starter starter;
public Engine(Starter starter) {
this.starter = starter;
}
void engageStarter() {
starter.spin();
}
}
public static class Starter {
public void spin() {
System.out.println("Start or explode");
}
}
}
答案 0 :(得分:0)
解决方案是使engageStarter()公开。