如何使用JUnit + Mockito模拟您尝试进行单元测试的服务中使用的类 [英] How do you mock classes that are used in a service that you're trying to unit test using JUnit + Mockito

查看:136
本文介绍了如何使用JUnit + Mockito模拟您尝试进行单元测试的服务中使用的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为使用/依赖于另一个类的服务编写单元测试。我想做的是模拟依赖的行为(与该类的实例相对)。正在测试的服务方法在内部使用依赖类(即依赖类的实例未传入方法调用)所以例如我有一个我想要测试的服务方法:

I want to write a unit test for a service that uses/depends on another class. What i'd like to do is mock the behavior of the dependent class (As opposed to an instance of that class). The service method being tested uses the dependent class internally (i.e. an instance of the dependent class isn't passed in to the method call) So for example I have a service method that I want to test:

import DependentClass;

public class Service {

    public void method() {
        DependentClass object = new DependentClass();
        object.someMethod();
    }
}

在我的服务方法()的单元测试中,我想在DependentClass实例上模拟someMethod()而不是让它使用真实的。我如何在单元测试中进行设置?

And in my unit test of Service method(), I want to mock someMethod() on the DependentClass instance instead of having it use the real one. How do I go about setting that up in the unit test?

我见过的所有示例和教程都显示了传递给方法的模拟对象实例测试,但我没有看到任何显示如何模拟而不是对象实例

All of the examples and tutorials i've seen show mocking object instances that are passed in to the method being tested, but I haven't seen anything showing how to mock a class as opposed to an object instance.

这可能与Mockito(当然是)?

Is that possible with Mockito (Surely it is)?

推荐答案

使用 Powermockito 框架和 whenNew(...)方法。测试示例如下:

It's easy with Powermockito framework and whenNew(...) method. Example for your test as follows:

   @Test
   public void testMethod() throws Exception {
      DependentClass dependentClass = PowerMockito.mock(DependentClass.class);
      PowerMockito.whenNew(DependentClass.class).withNoArguments().thenReturn(dependentClass);

      Service service = new Service();
      service.method();
   }

希望有所帮助

这篇关于如何使用JUnit + Mockito模拟您尝试进行单元测试的服务中使用的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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