Android/Testing/Unit Testing/Injecting Static Methods

You cannot redefine a static method by inheritance, but you will often want to provide a test implementation of static methods (which include the 'new' operator).

A tool like PowerMock does allow for the redefinition of static methods, but if you don't get along with it, you can still work around the issue: if you're using dependency injection, you can write trivial classes to wrap static methods and substitute them with little intrusion into your code. If you're not using real DI (due to the start-up time, for instance), the following may help you start.

If you decide to stick with this manual DI, you may find that certain methods (particularly Android ones) turn up regularly enough in different classes' tests to make it worth creating an external non-static utility class to inject. There'd be a temptation to let this grow into a grab-bag class containing all the statics you have ever needed (which probably isn't a problem beyond being a sprawling mess and potentially concealing that a class under test is doing too much), but you would want to guard against the temptation to sneak in things which aren't strictly statics "because it's a handy singleton in which to hide a bit of state" (which would be wrong).

If you're a fan of 'single responsibility', you'll see that this StaticInjection should really be broken up into separate chunks - the beginnings of proper full-scale DI (albeit static DI, rather than the dynamic style of Guice etc.).

Code under test
Adding an inner class allows you to provide default behaviour in a production environment, but special behaviour in tests. The example shows that it's not just Android that likes declaring methods static.

If you find your StaticInjection class growing too much, you're probably doing too much in your Activity - try to follow the 'single responsibility' principle.

Test
A test would either subclass and override bits of StaticInjection, or use mocking to constrain which bits of the StaticInjection were used:

Misc
The above example depends on these trivial classes: