Unit testing a method which is inside an Android Activity

Viewed 2502

I don't know if it has been answered or not, I found some similar questions but the answers are not making any sense to me. So, I am asking it again.

How can we test a method which is inside an activity.

public class MyActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       //inflate layout        
   }

   public int someMethod() {
       //perform some logic and return an integer
   }

}

I want to unit test the method someMethod but how can I do this as I cannot create an instance of the activity and directly call that method. The method under test does not use any android component so I dont want to use Roboelectric or any other such libraries or tools. It is a plain java method.

One way I know is to move the method to another class and have that class unit tested and I am perfectly fine with it, but I wanted to know if that is the right way, (create a separate class just for this purpose), or is there any other way to do it?

Thank you for any feedback.

1 Answers

To go a bit into theory, you do not want to test a single method in another class. Following S.O.L.I.D. and D.R.Y. principles, your classes shall have a single responsibility. So if you think that you want to test only one single method, this method clearly has another responsibility than the rest of the class. Which leads us to: It should not be in that particular class.

Unit Tests are only as good (and as valuable) as the plan behind the testing.

To answer your question: Yes you can call a new myActivitiy() and the unit test might run it (at least I think so). But if the method uses runtime values / context or any other thing from that activity, you can't without running Espresso or similar frameworks.

I recommend to create a proper object model that is testable.

Unit tests can only test code that is written testable

cheers, Gris

Related