Use Mockito to unit test a function which contains static method call & async task

∥☆過路亽.° 提交于 2019-12-25 06:55:05

问题


I have a helper class which contains an public static method getProductHandler(String name):

public class ProductHandlerManager {
  public static Handler getProductHandler(String name) {
        Handler handler = findProductHandler(name);
        return handler;
  }
}

A CustomerService class uses the above ProductHandlerManager:

public class CustomerService {
   ...
   public void handleProduct() {
     Handler appleHandler = ProductHandlerManager.getProductHandler("apple");
     appleHandler.post(new Runnable() {
        @Override
        public void run() {
           //...
        }
     });
   }
}

I want to unit test handleProduct() method in CustomerService class. I tried using mockito to mock the ProductManager.getProductHandler("apple") part in test, however, mockito doesn't support static method mocking. How can I use Mockito to unit test handleProduct() function then?

Please don't suggest me to use Powermock, since I read some article which says if I need to mock static method, it indicates a bad design. But I can accept suggestions about code refactoring to make it testable.


回答1:


You can refactor and specify a Handler yourself. These can often be package private, if you put your tests in the same package as your classes-under-test—even if they're in a different source folder (e.g. src vs testsrc). Guava (Google Commons) has a handy @VisibleForTesting documentation annotation, too, though Javadoc tends to work as well.

public class CustomerService {
  public void handleProduct() {
    handle(ProductHandlerManager.getProductHandler("apple"));
  }

  /** Visible for testing. */
  void handleProduct(Handler handler) {
    handler.post(new Runnable() {
       @Override
       public void run() {
          //...
       }
    });
  }
}

At this point, you can test handleProduct(Handler) intensively as a unit test, then only test handleProduct() as an integration test to ensure the "apple" product handler interacts correctly.



来源:https://stackoverflow.com/questions/33610230/use-mockito-to-unit-test-a-function-which-contains-static-method-call-async-ta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!