mockitopowermockito

How to mock for such scenario(getValue1 call getValue2/.../getValue5)


I have following simple code to illustrate what I want to ask: I have a class MyClass, it has 5 methods, getValue1 ... getValue5.

In the implementation, calling getValue1 will call getValue2/getValue3/getValue4/getValue5 in the code path.

I want to test method getValue1,getValue1 will call getValue2->getValue3->getValue4->getValue5,the getValueX methods below look very simple, but may be very complicated in real and hard to call when testing getValue1

What i want to do is when i test getValue1 ,I want to mock the call of getValue2 (so that getValue1 will cut off from getValue2/getValue3/getValue4/getValue5),

That means, getValue1 will run in real mode, while getValue2 will run in mock mode, I would ask how to do it with PowerMockito

Thanks.

import org.junit.Test;
import org.mockito.InjectMocks;

class MyClass {
    public String getValue1() {
        String value = getValue2();
        return value;
    }

    public String getValue2() {
        //some code here
        String value = getValue3();
        //some code here
        return value;
    }

    public String getValue3() {
        //some code here
        String value = getValue4();
        //some code here
        return value;
    }

    public String getValue4() {
        //some code here
        String value = getValue5();
        //some code here
        return value;
    }

    public String getValue5() {
        //some code here
        return "value5";
    }
}

public class MyClassTest {

    @InjectMocks
    MyClass obj;

    @Test
    public void testGetValue1() {
        obj.getValue1();
    }
}

Solution

  • It can be done using Mockito.spy. Which allow you to partially mock some method of a real object.

    import org.junit.jupiter.api.Test;
    
    import static org.junit.jupiter.api.Assertions.assertEquals;
    import static org.mockito.Mockito.spy;
    import static org.mockito.Mockito.when;
    
    public class MyClassTest {
        @Test
        public void testGetValue1() {
            MyClass myClass = spy(new MyClass());
            when(myClass.getValue2()).thenReturn("value2");
    
            assertEquals("value2", myClass.getValue1());
        }
    }