BrianP
BrianP

Reputation: 1877

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)?

Upvotes: 5

Views: 6203

Answers (2)

troig
troig

Reputation: 7212

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

Upvotes: 4

StackFlowed
StackFlowed

Reputation: 6816

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

Upvotes: 1

Related Questions