If you need a new instance in every call, I would suggest refactoring as follows:
class ClassToTest { public doSomething () { SomeObject a = getInstance(); a.doSomethingElse (); } protected SomeObject getInstance() { return new SomeObject(); } }
You can then create a test class that extends ClassToTest by overriding the getInstance () method, one of which provides a mock object.
This, of course, is only viable if you are okay with the expansion of the getInstance () method, so I do not recommend it if the class is part of the public API. If so, consider supplying a factory class using dependency injection.
source share