User Mockito to unit test a function doing async task in my case

后端 未结 1 427
面向向阳花
面向向阳花 2021-01-07 13:54

In my Android project, I have a class extends HandlerThread:

public class MyHandlerThread extends HandlerThreads {
   private Handler mHandl         


        
1条回答
  •  再見小時候
    2021-01-07 14:21

    WHAT do you want to test? MyWorker? MyHandlerThread? the anonymous MyAsyncTask? All toegether? Probably a bad idea, especially if the anonymous MyAsyncTask relies on an actual server response (which would prevent this from being a good unit test, since you are testing a whole system then). So, I would split the whole thing into parts and test all these parts seperately. If you have done so, then you can check multiple parts toegether against a real server with an integration tests.

    To test the MyHandlerThread, you could for example introduce a HandlerFactory, mock that and thus ensure that the handler was called correctly.

    public class MyHandlerThread extends HandlerThreads {
       private HandlerFactory handlerFactory; // <- Add setter
       …
       public void doAsyncTask(MyAsyncTask task) {
            Handler mHandler = handlerFactory.createHandler(this.getLooper());
            mHandler.post(task);
        }
    }
    

    Easily testable unit. MyAsyncTask is short and abstract, honestly, I wouldn't test that. Not much to gain there, since it doesn't actually do much. And the MyWorker ? Depends, but you could, for example, add a getter/setter for the MyHandlerThread, allowing you to mock that. Extracting your anonymous class into a real one would probably allow you to test that one, too, independent of the others.

    0 讨论(0)
提交回复
热议问题