How can I call the actual constructor of a mocked mockito object?

11,314

Solution 1

You can use Mockito.spy (http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#spy):

baseClass object = new baseClass(new FetchData());
baseClass spy = Mockito.spy(object);

Mockito.when(spy.parse()).thenCallRealMethod();
Mockito.when(spy.transform()).thenReturn("Something");

Solution 2

Your problem is of a different nature: you created hard to test code. That is the thing with constructors: one has to be really careful about what they are doing.

The other thing is that you directly "ran" into "prefer composition over inheritance". It might be tempting to simply extend some other class to inherit some helpful behavior - but when you are doing that, you run exactly in such kind of problems!

My kinda non-answer: step back, and have a close look into your design if that is really the best solution. Probably you watch those videos first to understand what I am talking about. If you have some experienced folks around, talk to them; and have them review your design.

Share:
11,314
Vivek Santhosh
Author by

Vivek Santhosh

Updated on June 19, 2022

Comments

  • Vivek Santhosh
    Vivek Santhosh almost 2 years

    I have code similar to this

    class superClass {
        public String transform(String str) {
            //lots of logic including ajax calls
            return("Modified"+str);
        }
    }
    
    class baseClass extends superClass {
        private FetchData fetchData;
        baseClass(FetchData fetchData) {   
            this.fetchData = fetchData;
        }
    
        public String parse() {
            String str = fetchData.get();
            //some more logic to modify str
            return transform(str);
        }
    }
    

    and I am using mockito and junit to test it. I am mocking the baseClass and doing something like this

    baseClass baseMock = Mockito.mock(baseClass.class);
    Mockito.when(baseMock.parse()).thenCallRealMethod();
    Mockito.when(baseMock.transform()).thenReturn("Something");
    

    How can I inject the mock fetchData, as it is injected through the constructor?

  • Vivek Santhosh
    Vivek Santhosh over 7 years
    Awesome,that works thanks :) one question, how can i call the actual method with the do syntax because the Mockito.when(spy.parse()).thenCallRealMethod(); calls the actual method, when that mock line executes, i want the method to be called only when i call spy.parse()
  • Ashley Frieze
    Ashley Frieze over 7 years
    Mockito.doCallRealMethod().when(<objectInstance>).<method>()‌​; However, please look at @GhostCat 's post below. What you appear to be trying to test doesn't make sense. Or, if you're just trying to test an abstract base class, perhaps don't use mockito. Make a subclass of it in your test class and use that.