|
15 | 15 | import static org.junit.Assert.assertEquals;
|
16 | 16 | import static org.junit.Assert.assertNotNull;
|
17 | 17 | import static org.junit.Assert.assertNull;
|
| 18 | +import static org.junit.Assert.assertTrue; |
18 | 19 |
|
19 | 20 | import java.util.ArrayList;
|
20 | 21 | import java.util.Arrays;
|
21 | 22 | import java.util.List;
|
| 23 | +import java.util.concurrent.TimeUnit; |
22 | 24 |
|
23 | 25 | import org.junit.Before;
|
24 | 26 | import org.junit.Test;
|
@@ -351,4 +353,49 @@ public void testResponseMessage() {
|
351 | 353 | assertEquals("The response status message should be 'No Content'.", "No Content", response.getStatusMessage());
|
352 | 354 | }
|
353 | 355 |
|
| 356 | + /** |
| 357 | + * Test canceling a service call by mimicking setting a timeout and canceling if the call exceeds that value. |
| 358 | + * |
| 359 | + * @throws InterruptedException the interrupted exception |
| 360 | + */ |
| 361 | + @Test |
| 362 | + public void testRequestCancel() throws InterruptedException { |
| 363 | + server.enqueue(new MockResponse().setBody(testResponseBody1).setBodyDelay(5000, TimeUnit.MILLISECONDS)); |
| 364 | + |
| 365 | + // time to consider timeout (in ms) |
| 366 | + long timeoutThreshold = 3000; |
| 367 | + final boolean[] hasCallCompleted = {false}; |
| 368 | + final boolean[] callWasCanceled = {false}; |
| 369 | + |
| 370 | + ServiceCall<TestModel> testCall = service.getTestModel(); |
| 371 | + long startTime = System.currentTimeMillis(); |
| 372 | + testCall.enqueue(new ServiceCallback<TestModel>() { |
| 373 | + @Override |
| 374 | + public void onResponse(Response<TestModel> response) { |
| 375 | + hasCallCompleted[0] = true; |
| 376 | + System.out.println("We got a response!"); |
| 377 | + } |
| 378 | + |
| 379 | + @Override |
| 380 | + public void onFailure(Exception e) { |
| 381 | + callWasCanceled[0] = true; |
| 382 | + System.out.println("The request failed :("); |
| 383 | + } |
| 384 | + }); |
| 385 | + |
| 386 | + // keep waiting for the call to complete while we're within the timeout bounds |
| 387 | + while (!hasCallCompleted[0] && (System.currentTimeMillis() - startTime < timeoutThreshold)) { |
| 388 | + Thread.sleep(500); |
| 389 | + } |
| 390 | + |
| 391 | + // if we timed out and it's STILL not complete, we'll just cancel the call |
| 392 | + if (!hasCallCompleted[0]) { |
| 393 | + testCall.cancel(); |
| 394 | + } |
| 395 | + |
| 396 | + // sleep for a bit to make sure all async operations are complete, and then verify we set this value |
| 397 | + // in onFailure() |
| 398 | + Thread.sleep(500); |
| 399 | + assertTrue(callWasCanceled[0]); |
| 400 | + } |
354 | 401 | }
|
0 commit comments