2

Long story short, I need to test code executed in the "doInBackground" method of AsyncTask.

This in Android Studio with PowerMockito / Mockito / Robolectric / JUnit4.

I am aware testing written code is far from ideal,
but I have no word in this and I can't change the original code.

This is the case :

   public void methodToTest(){
     new AsyncTask<Integer, Void, Boolean>() { 
        @Override
        protected Boolean doInBackground(Integer... integers) {

           //How to test code written over here ?

           return false;
        }
     }
  }

Is there a way to solve this ? Any suggestions are very much appreciated

  • Did you see http://stackoverflow.com/questions/15035850/testing-async-tasks-with-robolectric? – Eugen Martynov Apr 07 '17 at 08:15
  • @EugenMartynov I did not came across that one during my Google quest. That one is about verifying the AsyncTask itself if I'm correct ? my goal is to test the code used in the doInBackground method of the AsyncTask. Please correct me if I'm Wrong. – user2417217 Apr 07 '17 at 09:39
  • Ah, I missed that you want to test abstract class. You can always extend it in tests and implement abstract methods in dummy way if needed – Eugen Martynov Apr 07 '17 at 10:58

1 Answers1

0

There is an ugly but working detour here: reflection.

The point is: the above code declares an anonymous inner class. But thing is: even anonymous inner classes have a unique, defined name.

And using reflection, it is perfectly possible to instantiate objects of such anonymous inner classes.

You can have a look here to get an idea how that would work.

Boiling down to: when you are able to instantiate an object of the class that contains methodToTest(); then you are also able to instantiate objects of that inner class. And then you should be able to call methods on either of these objects.

But even when that works and gets you to reasonable unit tests: you probably want to show the people writing the production code those tests. To make it clear to them what kind of harm their unwillingness to write testable production code is causing!

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Thank you very much for the detailed answer. I will certainly discuss this matter as this case is bad. But in the meantime I will check out the provided example and see if it works ! – user2417217 Apr 06 '17 at 14:09