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