0

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Nilotpal
  • 3,237
  • 4
  • 34
  • 56
  • 1
    You can't. What you've identified is a problem with the design of the code - it's tightly coupled to a concrete implemenation. – jonrsharpe May 21 '21 at 16:38

1 Answers1

1

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.

Suraj Gautam
  • 1,524
  • 12
  • 21