0

I'm new to java. While working on a requirement Where I need to write test cases for a utility class, there exists lines as seen below :

HttpURLConnection con =null; 


 if (T.equalsIgnoreCase(sslCheck)) { 

con = HttpsURLServiceUtil.openHttpURLConnection(sslURLDetails); 

} else if (F.equalsIgnoreCase(sslCheck)) { 

con= (HttpURLConnection) urlObj.openConnection(); 

} 

} else { 

con = (HttpURLConnection) urlObj.openConnection(); 

} 

So i want to mock the lines where there are dependencies

con=HttpsURLServiceUtil.openHttpURLConnection(sslURLDetails);

con= (HttpURLConnection) urlObj.openConnection(); 

The issue is I tried mocking the static method openHttpURLConnection using power mockito and Mockito in-line but everytime when I mock I'm getting null as the value of the connection object con. Because of that, I'm getting null pointer exception in the line

con.setRequestMethod ("POST"); 

Because of this exception the control is getting transferred to catch block which is located 200 lines from the above line. Therefore I'm not able to cover the inbetween lines since whenever I mock I'm getting null pointer exception. Could anybody help me to mock the dependency behaviour using Mockito/Mockito-inline in such a way that it establishes dummy connection and returns a dummy connection object with non null value. Please refer the sample sslURLDetails map values. We can use any values in values field if needed.

sslURLDetails refers to map and please find the sample map with keys as seen below:

Map<String, String> sslURLDetails= new LinkedHashMap<>(); 

ss1URLDetails.put("MPOWER_SSL_RTCS_URL1", "https://"); ss1URLDetails.put("SSL_KEY_STORE_FILENAME", "C:/Users/Desktop/certs/XYZ/report.jks"); ss1URLDetails.put("SSL_TRUST_STORE_FILE_NAME", "C:/Users/Desktop/certs/XYZ/report.jks"); sslURLDetails.put("SSL_USER_PASSCODE", ""); 

sslURLDetails.put("SSL_KEY_STORE_TYPE", "JKS"); 

ss1URLDetails.put("SSL_URL_ENABLED", "true");
VoiceOfUnreason
  • 52,766
  • 5
  • 49
  • 91
ASR
  • 1
  • 1
  • In C# which is fairly similar to Java, you can [only replace virtual methods with Test Doubles](https://stackoverflow.com/a/1973482/126014). As far as I know, this also applies in Java. – Mark Seemann Dec 31 '22 at 11:03

1 Answers1

0

You haven't really given any context to how this method is used but are you able to refactor your code, it will be much easier to change your static method and implement it with dependency injection?

If that's not an option there are libraries that can mock or stub static methods (e.g. Fakes in .net but I'm not a java chap so you'd need to research what is available in your stack).

lazarus
  • 371
  • 2
  • 10