Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Is that possible with Mockito (Surely it is)?

like image 603
BrianP Avatar asked Sep 23 '14 17:09

BrianP


People also ask

How do you make a mock in Mockito?

Mockito mock method We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.

Which method is used to mock the service methods response?

Mockito when() method It should be used when we want to mock to return specific values when particular methods are called. In simple terms, "When the XYZ() method is called, then return ABC." It is mostly used when there is some condition to execute.


2 Answers

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

Hope it helps

like image 173
troig Avatar answered Sep 24 '22 17:09

troig


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();
    }
}
like image 35
StackFlowed Avatar answered Sep 25 '22 17:09

StackFlowed