Chang Liu Chang Liu - 3 months ago 14
Java Question

Using Mockito to mock a class method inside another class

I'm trying to write unit tests with Mockito / JUnit for a function like this:

class1 {
method {
object1 = class2.method // method that I want to fake the return value
// some code that I still want to run

Is there any way in Mockito to stub the result of class2.method? I'm trying to improve code coverage for class1 so I need to call its real production methods.

I looked into the Mockito API at its spy method but that would overwrite the whole method and not the part that I want.


I think I am understanding your question. Let me re-phrase, you have a function that you are trying to test and want to mock the results of a function called within that function, but in a different class. I have handled that in the following way.

public MyUnitTest {
    private static final MyClass2 class2 = mock(MyClass2.class);

    public void setupTests() {
        when(class2.get(1000)).thenReturn(new User(1000, "John"));

    public void testFunctionCall() {
        String out = myClass.functionCall();

What this is doing is that within the function wrapped with the @Before annotation, I am setting up how I want the functions in class2 to respond given specific inputs. Then, from within the actual test, I am just calling the function that I am trying to test in the class I want to test. In this case, the myClass.functionCall() is running through as normal and you are not overwriting any of its methods, but you are just mocking the outputs that it gets from the methods (or method) within MyClass2.