简体   繁体   English

如何模拟试图使用JUnit + Mockito进行单元测试的服务中使用的类

[英]How do you mock classes that are used in a service that you're trying to unit test using 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 (ie 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();
    }
}

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. 在我对Service method()的单元测试中,我想在DependentClass实例上模拟someMethod(),而不是让它使用真实的实例。 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 . 我看过的所有示例和教程都显示了模拟对象实例,这些实例实例已传递到要测试的方法中,但是我还没有看到任何东西显示出如何模拟而不是对象实例

Is that possible with Mockito (Surely it is)? Mockito可以做到吗(肯定是)?

It's easy with Powermockito framework and whenNew(...) method. 使用Powermockito框架和whenNew(...)方法很容易。 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();
   }

Hope it helps 希望能帮助到你

This is a problem of poor design. 这是设计不良的问题。 You can always take in the param from a package private constructor. 您始终可以从包私有构造函数中获取参数。 Your code should be doing something like this: 您的代码应执行以下操作:

public class Service {

    DependentClass object;
    public Service(){
        this.object = new DependentClass();
    }

    Service(DependentClass object){ // use your mock implentation here. Note this is package private only.
     object = object;
    }

    public void method() {        
        object.someMethod();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM