logger
logger

Reputation: 2053

Mockito method call without object

The code has something like

Speed speed = readSpeed(Point A, Point B);
isOverLimit = limitCheck.speedCheck(speed);

How do I use mockito for read speed?

Mockito.when(readSpeed(0, 0).then...

suppose should I use the class object to call this?

Upvotes: 2

Views: 3753

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95634

Mockito effectively works by creating individual subclasses of objects that delegate every overridable implementation to the mock framework.

Consequently, you can't use Mockito mock your method (readSpeed) for all instances at once or instances created in your system under test, nor mock any static or final methods. If readSpeed is any of those, or need to be mocked on an instance you don't touch in your test, Mockito will not work for you; you'll need to refactor, or use PowerMockito (which quietly rewrites your system under test to redirect constructors, final calls, and static calls to Mockito's framework).

If readSpeed is a public non-final instance method on your system under test, then you can mock it, and that'd be called a partial mock of your component. Partial mocks can be useful, but can also be considered "code smells" (as mentioned in the Mockito documentation): Ideally your test class should be an atomic unit to test, and mocking should happen for the dependencies around your system under test rather than your test itself. Otherwise, you could too easily test the spec or test the mocking framework rather than testing your component.

Though the better thing to do would be to split the class into smaller interconnected components, you can use partial mocking in Mockito like this:

@Test public void componentChecksSpeed() {
  YourComponent yourComponent = Mockito.spy(new YourComponent());

  // Use doReturn, because the when syntax would actually invoke readSpeed.
  doReturn(65).when(yourComponent).readSpeed(any(Point.class), any(Point.class));

  yourComponent.run();
}

Upvotes: 4

Related Questions