使用Mockito和PowerMockito模拟类对象 [英] Mocking a class object using Mockito and PowerMockito

查看:435
本文介绍了使用Mockito和PowerMockito模拟类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Mockito和/或PowerMockito模拟类对象?

Is it possible to mock a class object using Mockito and/or PowerMockito?

类似的东西:

Class<Runnable> mockRunnableClass = mock(Class<Runnable>.class);

推荐答案

模拟类的替代方法可能是使用Factory.我知道您担心重构,但这可以在不更改类的公共API的情况下完成.您没有提供太多代码来理解要测试的类,但是这里有一个无需更改API即可重构的示例.这是一个琐碎的课程,但可能会给您一个想法.

An alternative to mocking Class might be to use a Factory instead. I know you are concerned about refactoring, but this could be done without changing the public API of the class. You haven't provided much code to understand the class you are trying to test, but here's an example of refactoring without changing the API. It's a trivial class, but it might give you an idea.

public class Instantiator {

  public Runnable getNewInstance(Class<Runnable> runnableClass) throws Exception {
    return runnableClass.newInstance();
  }
}

当然,测试这个琐碎的类最简单的方法是使用真正的Runnable类,但是如果您尝试模拟该类,则会遇到问题.因此,您可以这样重构它:

Of course, the easiest thing to do to test this trivial class would be to use a genuine Runnable class, but if you tried to mock the Class, you would run into the problems you're having. So, you could refactor it thus:

public class PassThruFactory {
  public Object newInstance(Class<?> clazz) throws Exception {
    return clazz.newInstance();
  }
}

public class Instantiator {
  private PassThruFactory factory = new PassThruFactory();

  public Runnable getNewInstance(Class<Runnable> runnableClass) throws Exception {
    return (Runnable)factory.newInstance(runnableClass);
  }
}

现在,Instantitiator可以使用相同的公共API完全完成它以前所做的(非常简单)的事情,而该类的任何客户端都不需要自己进行任何特殊的注入.但是,如果您想模拟工厂类并注入它,那很容易做到.

Now Instantiator does exactly the (trivially simple) thing it was doing before with the same public API and no need for any client of the class to do any special injecting of their own. However, if you wanted to mock the factory class and inject it, that's very easy to do.

这篇关于使用Mockito和PowerMockito模拟类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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