0

My class under test is ClassA which in one of its private method uses a static factory (lets say CarFactory) method getCar(XXX xxx) which returns a Car.

Part of the CarFactory logic is to validate that the given xxx parameters meets some criteria.

I tried using Mockito like the following:

@Mock private Car mockForCar;
@Mock private XXX xxxMock;

...

when(CarFactory.getCar(xxxMock)).thenReturn(mockForCar);

But I get an exception regarding that xxxMock isn't valid by the CarFactory.

Why is the real getCar(xxx) method gets called and not the stubbed one?

Is there a better way doing this?

Daniel L.
  • 5,060
  • 10
  • 36
  • 59

1 Answers1

0

From the Mockito FAQ:

Can I mock static methods?

No. Mockito prefers object orientation and dependency injection over static, procedural code that is hard to understand & change. If you deal with scary legacy code you can use JMockit or Powermock to mock static methods.

If you want to stub this using Mockito, you should make it non-static and inject the factory. And that's better OO design anyway.

Don Roby
  • 40,677
  • 6
  • 91
  • 113