How to mock "new" created objects inside a method in Mockito

311 views Asked by At

I have a legacy code where the code looks like below :

public String getToken() {

HttpURLConnection urlConnection = (HttpURLConnection)(new URL(endpoint).getConnection();
..
}

How to mock a new URL(endpoint).getConnection(). Until I get a mocked urlConnection, I can't proceed into further statements of the method.

1

There are 1 answers

0
Suraj Gautam On

You can't mock this piece of code. Why?

Let's say you mocked the URL object but when the code reaches this part of the code, new URL(endpoint) the new URL object is always created.

This is a bad design and the best thing you can possibly do is to inject the object into the constructor which makes the code easily testable as you can mock it.