I'm trying to mock org.apache.http.impl.client.DefaultHttpClient
using jmockit
I specially interested in mocking method DefaultHttpClient.execute()
I cannot seem to figure out why it doesn't work. I can confirmed that jmockit work fine for other class and method that I mocked.
Below is a sample of the code.
Can anyone tell me why the mocking of org.apache.http.impl.client.DefaultHttpClient
does not work?
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import mockit.Injectable;
import mockit.Mock;
import mockit.MockUp;
import mockit.Mocked;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import org.junit.Before;
import org.junit.Test;
import com.protecode.authenticationmodule.login.Login;
@SuppressWarnings("deprecation")
public class QueryTester2 {
@Mocked HttpUriRequest uriRequest;
@Injectable HttpContext context;
@Before
public void init() {
new MockLoginClass2();
new MockDefaultHttpClient2();
}
@Test
public void QueryTester2_Test1() {
try {
// Works! True, or whatever the mocked value below
System.out.println(Login.isLdapUser("john"));
HttpClient c = new DefaultHttpClient();
// Failed! Still prints "org.apache.http.impl.client.DefaultHttpClient@44f54792"
// instead of "mockedResponseToString"
System.out.println(c.toString());
//Failed! I don't see the println of "Mocked DefaultHttpClient.execute"
c.execute(uriRequest, context);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Mocks
@SuppressWarnings("deprecation")
class MockDefaultHttpClient2 extends
MockUp<org.apache.http.impl.client.DefaultHttpClient> {
@Mock
public String toString() {
System.out.println("mockedResponseToString");
return "mockedResponseToString";
}
@Mock
public HttpResponse execute(HttpUriRequest httpPost, HttpContext context)
throws IOException, ClientProtocolException {
System.out.println("Mocked DefaultHttpClient.execute");
HttpServletResponse response = (HttpServletResponse) new org.eclipse.jetty.client.HttpResponse(
null, null);
return (HttpResponse) response;
}
}
class MockLoginClass2 extends MockUp<Login> {
@Mock
protected static boolean isLdapUser(final String username) {
return true;
}
}
It seems that I made a mistake in my code above. Jmockit does not execute the mocked method because the signature that I gave is faulty.
@Mock
public HttpResponse execute(HttpUriRequest httpPost, HttpContext context) throws IOException, ClientProtocolException {
After changing it to the following code, jmockit successfully mocked or "replace" the original method.
@Mock
public CloseableHttpResponse execute(HttpUriRequest httpReq, HttpContext context) throws IOException, ClientProtocolException {