Reputation: 211
I was wondering how should I go about injecting a mocks - we have bunch of classes that do server calls, however our CI system can not access external resources and thus will not make a call to a server. Thus, the call has to be simulated and hardcoded values (such as response codes) needed to be return.
So, here is a snippet of a code:
HttpPost httpRequest = new HttPost(uri);
//some code here
try{
httpRequest.setEntity(entity);
HttpResponse response = httpClient.execute(httpRequest);
...
//other, irrelevant, code is here
So, is it possible to inject a mock into httpClient.execute(httpRequest) and return hardcoded response entity from a test unit?
Thank you
Upvotes: 1
Views: 1103
Reputation: 2025
Usually mocking some object looks like this:
public class TestClass {
private HttpServer server;
public HttpServer getServer() {
return server;
}
public void setServer(HttpServer server) {
this.server = server;
}
public void method(){
//some action with server
}
}
And test class:
public class TestClassTest {
//class under test
TestClass test = new TestClass();
@org.junit.Test
public void testMethod() throws Exception {
HttpServer mockServer = Mockito.mock(HttpServer.class);
test.setServer(mockServer);
//set up mock, test and verify
}
}
Here you some useful links:
Upvotes: 2