Search code examples
javajunitpowermockpowermockito

How do I mock a locally created object?


This is my class.

class Test {
    public void print(){
        RestTemplate restTemplate = new RestTemplate(); 
        restTemplate.getForObject("url", String.class);
    }
}

to test this class, I want to mock "RestTemplate". Is there any way to do this without changing the code.


Solution

  • That can't be done without changing the code, at least not in an elegant way.

    You create a new instance of RestTemplate each time you enter the print() method, so there's no way to pass in a mock.

    Slightly change the method to use RestTemplate as a parameter. At runtime this will be an actual instance of RestTemplate, but when unit testing the method it's able to accept a mock.

    class Test {
        public void print(RestTemplate restTemplate){
            restTemplate.getForObject("url", String.class);
        }
    }
    
    class TestTest {
    
        private final Test instance = new Test();
    
        @Test
        public testPrint() {
            RestTemplate restTemplateMock = mock(RestTemplate.class);
    
            instance.print(restTemplateMock);
    
            // TODO: verify method calls on the mock
        }
    }