简体   繁体   中英

How to mock static method which will try to establish HttpsURLConnection and will return a connection Object of type HttpsURLConnection using Mockito

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");

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 (eg Fakes in .net but I'm not a java chap so you'd need to research what is available in your stack).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM