Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test private functions in Android

Can we do unit testing of private functions and fields for Android Application using Android Mock ?

If yes, please explain how ?

like image 621
Sachchidanand Avatar asked Jan 12 '12 11:01

Sachchidanand


People also ask

Can we write unit test for private methods?

Why We Shouldn't Test Private Methods. As a rule, the unit tests we write should only check our public methods contracts. Private methods are implementation details that the callers of our public methods aren't aware of. Furthermore, changing our implementation details shouldn't lead us to change our tests.

Can I test private methods with JUnit?

So whether you are using JUnit or SuiteRunner, you have the same four basic approaches to testing private methods: Don't test private methods. Give the methods package access. Use a nested test class.

Should I unit test private method?

Unit Tests Should Only Test Public Methods The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.

How do you cover a private method in a test class?

Annotate the mehod with @testVisible: Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only.


2 Answers

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

you can use Public and protected fields or methods in unit tests.

like image 112
Vinay Kumar Avatar answered Oct 07 '22 16:10

Vinay Kumar


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.

like image 40
rfsk2010 Avatar answered Oct 07 '22 15:10

rfsk2010