Unit test private functions in Android

Can we do unit testing of private functions and fields for an Android application using the Android Mock?

If yes, please explain how?

+8
source share
5 answers

Unit testing a private method just sounds a little wrong to me. Public and protected methods are candidates for unit testing. Just to test private methods, you can make this method public or create more tests of public methods that call a private method, and it checks the functionality of the kernel of a private method.

+6
source

After a year, I also clicked on a library to help test private methods and fields. I believe that on Android you still need to test private methods.

You want your activity methods to be closed so that other classes do not think that they can access it (the fragment may, but this is not good practice for me, it is better to use the pattern of the observed observer). Then you will get private fields and methods that you will only need to access using tests.

BoundBox does just that! The following is an example of a test that accesses 2 private fields for verification:

@UiThreadTest public void testCompute() { // given boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity()); // when boundBoxOfMainActivity.boundBox_getButtonMain().performClick(); // then assertEquals("42", boundBoxOfMainActivity.boundBox_getTextViewMain().getText()); } 
+2
source

Hi, I wrote an article in a blog article about this topic and I will show how you can achieve testing of internal methods, understanding the difference between the java package and the AndroidManifest "package".

As a result, you will use the same trick as traditionally in Java: let the methods to be tested be protected.

I hope this helps!

+1
source

The best and correct legal way to test a private method from the @VisibleForTesting test environment is according to the method, so the same method will be displayed for the test environment as a regular public method. here is the official link for annotation VisibleForTesting

+1
source

@VisibleForTesting (otherwise = VisibleForTesting.PROTECTED) private string field;

You can use open and protected fields or methods in unit tests.

0
source

Source: https://habr.com/ru/post/905815/


All Articles