Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 860
Vivek Santhosh Avatar asked Oct 31 '16 05:10

Vivek Santhosh


Video Answer


2 Answers

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");
like image 91
Strelok Avatar answered Oct 19 '22 06:10

Strelok


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.

like image 3
GhostCat Avatar answered Oct 19 '22 04:10

GhostCat