I recently discovered MockWebServer library and I try to use it in my project with Junit and mockito.
I have this test method:
@Test
public void testGetUsers() throws Exception {
MockWebServer server = new MockWebServer();
server.start();
MockResponse mockedResponse = new MockResponse();
mockedResponse.setResponseCode(200);
mockedResponse.setBody("{}");
server.enqueue(mockedResponse);
server.url("https://my-domain/user/api/users");
JSONObject result = UserService.getUsers();
assertNotNull(result);
server.shutdown();
}
My method getUsers() do the Http call :
public JSONObject getUsers() {
String urlUser = "https://my-domain/user/api/users";
Request request = new Request.Builder()
.url(urlUser)
.build();
Response response =
MyConf.getOkHttpClient().newCall(request).execute();
.... //process users and return a json Object
}
And here is my gradle configuration:
compile('com.squareup.okhttp3:okhttp:3.4.2')
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.1.0'
testImplementation 'com.squareup.okhttp3:mockwebserver:3.12.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.1.0'
testCompile 'org.junit.jupiter:junit-jupiter-params:5.1.0'
testCompile group: 'org.mockito', name: 'mockito-all', version: '1.8.4'
testCompile group: 'com.squareup.okhttp3', name: 'mockwebserver', version: '3.12.0'
When I launch the unit test, the http call is not mocked by Mockwebserver. I get a response from my real server and not the mocked response ("{}").
Can you help me with that ? Thanks in advance
My guess is that it doesn't work as you expect it. In the git readme they give the following code example:
// Ask the server for its URL. You'll need this to make HTTP requests.
HttpUrl baseUrl = server.url("/v1/chat/");
So you're getting a URL by the mock server you'll have to call, not an overwrite of any existing URL.
I just double checked this with the following source code:
MockWebServer server = new MockWebServer();
server.start();
HttpUrl baseUrl = server.url("/v1/chat/");
This gives for baseUrl
a new address: http://127.0.0.1:8125/v1/chat/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With