How do you mock the classes that are used in the service you are 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 would like to do is mock the behavior of the dependent class (as opposed to an instance of that class). The service method being checked uses the dependent class internally (that is, no instance of the dependent class is passed to the method call). 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 the service () method, I want to mock someMethod () on the DependentClass instance instead of using it. How do I set up a setup in a unit test?

All the examples and tutorials I've seen show funny object instances that are passed to the method under test, but I haven't seen anything showing how to mock a class rather than an object instance.

Is this possible with Mockito (is it true)?

+3


source to share


2 answers


It's easy with a frame Powermockito

and whenNew(...)

. An example of your test:

   @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

+4


source


This is a bad design problem. You can always take a parameter from a private package constructor. Your code should do 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();
    }
}

      

+1


source