Using Mockito, how can I mock a return value of an instance method without having an instance of that class?

Viewed 3906

I have a class called MyClass. I have a method in that class, public int getSpacing().

I am testing a method from a different class. public static ArrayList<SpecialObject> getSpecialObjects().

getSpecialObjects() calls getSpacing() on an instance of MyClass. I want this method to always return 0 when I am running a test with Mockito. How can I do this? All the examples I have found require a particular instance of an object before you can mock a method.

This is what I know how to do.

MyClass myInstance = new MyClass();        
Mockito.when(myInstance.getSpacing()).thenReturn(0);

However, I want to override the behavior of getSpacing() for ALL instances of MyClass, because the instances are created dynamically in getSpecialObjects(). How can I do this?

This is what I want to say but don't know how.

Mockito.when((Any instance of MyClass).getSpacing()).thenReturn(0);
2 Answers
Related