Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to local unit test private methods using Android library?

I have a public method which I'm unit testing. The method calls several private methods within the class. The problem is some of those private methods use Android resources like getString() and Html.fromHtml().

I know how to mock objects like Context.class using Mockito, but how do I mock objects that's not publicly accessible?

I tried Robolectric but it seems to cause a large number of NPEs due to uninitialised variables. The codebase is not mine and uses a lot of static methods so debugging them would be a last resort.

like image 226
geft Avatar asked Feb 17 '26 06:02

geft


1 Answers

Sadly, it's impossible to mock static methods, like Html.fromHtml() or even logging methods like Log.d(). You depend on Robolectric to help you out by providing implementations for you.

If you want to do full proper unit tests without Robolectric, you can mock things like Context and Resources using the gradle "test" target which adds mockable android infrastructure classes to you runtime classpath. You don't need third party software to do this. However, your tests will crash with a "Stubbed!" message for Android static methods calls. To avoid that, you have to wrap up all those static method calls into an object which you then mock during your tests. Kind of a pain.

like image 126
Doug Stevenson Avatar answered Feb 18 '26 19:02

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!