As kryger pointed out, you'd better redesign your code for testability:
public class ClassName {
public static <type> fun(HttpClient clientInstance){
response = clientInstance.execute();
//I am trying to mock response.execute
}
}
This is called dependency injection. Which is a fancy term for putting the burden on the caller of this code. J.B.Rainsberger wrote an excellent post about it.
If you can't modify the signature of fun()
because too many other code depends on it, then you can overload it:
public class ClassName {
/* this method is *not* going to be tested */
public static <type> fun(HttpClient clientInstance){
HttpClient clientInstance = null;
// clientInstance initialised here
return fun(clientInstance);
}
/* this method is going to be tested */
public static <type> fun(HttpClient clientInstance){
response = clientInstance.execute();
// mocking clientInstance.execute() will be easy now
}
}
What if the HttpClient
initialisation is tricky and you want to test it? You can refactor it into another method:
public class ClassName {
/**
* Package-private for testing reasons.
* Do not call it from within the class in production code!
*/
static HttpClient createHttpClient() {
HttpClient clientInstance = null;
// clientInstance initialised here
return clientInstance;
}
/* this method is *not* going to be tested */
public static <type> fun(HttpClient clientInstance){
HttpClient clientInstance = createHttpClient();
return fun(clientInstance);
}
/* this method is going to be tested */
public static <type> fun(HttpClient clientInstance){
response = clientInstance.execute();
// mocking clientInstance.execute() will be easy now
}
}
If everything else fails, you can use PowerMock to mock constructors. I've never seen a case where it was worth the trouble. Anyway, this Q&A explains how to use it.