santro
santro

Reputation: 393

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.

Upvotes: 4

Views: 726

Answers (2)

Luciano van der Veekens
Luciano van der Veekens

Reputation: 6577

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
    }
}

Upvotes: 4

Herr Derb
Herr Derb

Reputation: 5387

You want to use a injected instance of the RestTemplate for your tests.

@Autowired
private TestRestTemplate restTemplate;

In the test setup, you can mock the restTemplate's behavior as wanted.

Upvotes: 1

Related Questions