使用Mockito对包含静态方法调用&的函数进行单元测试.异步任务 [英] Use Mockito to unit test a function which contains static method call & async task

查看:359
本文介绍了使用Mockito对包含静态方法调用&的函数进行单元测试.异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个帮助器类,其中包含一个公共静态方法getProductHandler(String name):

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;
  }
}

CustomerService类使用上面的ProductHandlerManager:

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

我想对CustomerService类中的handleProduct()方法进行单元测试.我尝试使用 mockito 来模拟测试中的ProductManager.getProductHandler("apple")部分,但是,mockito不支持静态方法模拟.然后如何使用Mockito对handleProduct()函数进行单元测试?

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?

请不要建议我使用Powermock,因为我读过一些文章说如果我需要模拟静态方法,则表明设计不好.但是我可以接受有关代码重构以使其可测试的建议.

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.

推荐答案

您可以自己重构和指定Handler.如果您将测试与被测类放在同一包中,即使它们位于不同的源文件夹中(例如src vs testsrc),这些通常也可以是包私有的. 番石榴(Google Commons)具有方便的

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() {
          //...
       }
    });
  }
}

这时,您可以将handleProduct(Handler)作为单元测试进行大量测试,然后仅对handleProduct()作为集成测试进行测试,以确保"apple"产品处理程序能够正确交互.

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.

这篇关于使用Mockito对包含静态方法调用&的函数进行单元测试.异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆