Unit test private functions in Android

Hi posted a blog article about this topic and show how you can achieve to test internal methods by understanding the difference between a java package and AndroidManifest "package".

You will end up using the same trick as we do traditionally in Java : let methods to be tested be protected.

I hope that helps !


Unit testing a private method , just sounds a bit wrong to me . Public and protected methods are the candidates for unit testing. Just to test private methods , you can make the method public or create more tests of the public methods which call the private method, and tests the private method's core functionality.


One year after, I also pushed a library to help testing private methods and fields. I believe that on Android there is still a need to test private methods.

You wanna make your activities' methods private to prevent other classes from thinking they can access it (fragment can, but that is wrong practice to me, it's better to use an observable-observer pattern). Then you will end up with private fields and methods that would need to be accessed by tests only.

BoundBox does exactly that ! Here below is an example of a test that accesses 2 private fields of an activity to test it :

@UiThreadTest
public void testCompute() {
    // given
    boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity());

    // when
    boundBoxOfMainActivity.boundBox_getButtonMain().performClick();

    // then
    assertEquals("42", boundBoxOfMainActivity.boundBox_getTextViewMain().getText());
}