1

When I mock an object with Mockito.mock(), I expect the object to have stubbed out methods that return null, 0, false, et al, without having any of the code of the real object I'm mocking. I thought this was the default behavior in Java, but Android seems to involve the real objects as part of the mocks. How do I avoid this?

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");
    }
  }
}
Tremelune
  • 352
  • 2
  • 11

1 Answers1

0

The solution is to make engageStarter() public.

Tremelune
  • 352
  • 2
  • 11
  • Since I don't want to do this, I go in search of why Mockito doesn't stub out package-private methods... – Tremelune Feb 11 '15 at 18:51
  • The plot thickens: https://code.google.com/p/mockito/issues/detail?id=127 It seems that response #7 is on to something, as for this Android project, the source code being tested is in a different source directory. – Tremelune Feb 11 '15 at 18:52
  • 1
    It's due to classloaders. Package-private visibility only works when the classes are loaded by the same class loader. Mockito mocks are always loaded in their own class loader. – Jesse Wilson Feb 12 '15 at 01:57