As I discovered today, despite what all the other answers say, Foo x = new Foo(...) can indeed return null if the specified code works inside a test that uses PowerMock (or some other mocking structure with similar effects):
PowerMockito.whenNew(Foo.class).withAnyArguments().thenReturn(mockFoo);
In this case, the code of the constructor (s) Foo is generally excluded for new Foo(...) . But if you write a test in which you do not specify the layout in the above order, you can use null instead.
But even if you use such a framework, you do not need additional code in your classes, just to gracefully handle the case that you forgot to correctly mock objects in the test! This is not a real scenario when your code is meant to run. A code that is only ever active when testing should be eliminated in any case, in which case it will only ever act for a broken test.
Thus, even if you use PowerMock, this second line should rightfully be considered "dead code" and deleted.
Zac Thompson Oct 21 '15 at 0:26 2015-10-21 00:26
source share