75b84b2db8b4e85ed536a13ba9fe3f2b658c33d2
[vid.git] / vid-app-common / src / test / java / org / onap / vid / asdc / rest / RestfulAsdcClientTest.java
1 package org.onap.vid.asdc.rest;
2
3 import org.apache.commons.lang3.exception.ExceptionUtils;
4 import org.onap.vid.testUtils.TestUtils;
5 import org.testng.annotations.DataProvider;
6 import org.testng.annotations.Test;
7
8 import javax.ws.rs.NotFoundException;
9 import javax.ws.rs.ProcessingException;
10 import javax.ws.rs.client.Client;
11 import java.net.URI;
12 import java.util.UUID;
13 import java.util.function.Consumer;
14
15 import static org.hamcrest.CoreMatchers.instanceOf;
16 import static org.hamcrest.MatcherAssert.assertThat;
17 import static org.mockito.Matchers.any;
18 import static org.mockito.Mockito.when;
19 import static org.testng.AssertJUnit.fail;
20
21 public class RestfulAsdcClientTest {
22
23     @DataProvider
24     public static Object[][] javaxExceptions() {
25
26         return new Object[][] {
27                 {NotFoundException.class, (Consumer<Client>) javaxClientMock ->
28                         when(javaxClientMock.target(any(URI.class))).thenThrow(
29                                 new NotFoundException("HTTP 404 Not Found"))},
30                 {ProcessingException.class, (Consumer<Client>) javaxClientMock ->
31                         when(javaxClientMock.target(any(URI.class))).thenThrow(
32                                 new ProcessingException("java.net.ConnectException: Connection refused: connect"))},
33         };
34     }
35
36
37     @Test(dataProvider = "javaxExceptions")
38     public void whenJavaxClientThrowException_thenExceptionRethrown(Class<? extends Throwable> expectedType, Consumer<Client> setupMocks) throws Exception {
39         /*
40         Call chain is like:
41             this test -> RestfulAsdcClient ->  javax's Client
42
43         In this test, *RestfulAsdcClient* is under test (actual implementation is used), while javax's Client is
44         mocked to return pseudo-responses or - better - throw exceptions.
45          */
46
47         // prepare mocks
48         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
49         Client javaxClientMock = mocks.getFakeClient();
50
51         // prepare real RestfulAsdcClient (Under test)
52         RestfulAsdcClient restfulAsdcClient = new RestfulAsdcClient.Builder(javaxClientMock, new URI(""))
53                 .auth("")
54                 .build();
55
56         /// TEST:
57         setupMocks.accept(javaxClientMock);
58
59         try {
60             restfulAsdcClient.getServiceToscaModel(UUID.randomUUID());
61         } catch (Exception e) {
62             assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType));
63             return; //OK
64         }
65
66         fail("exception shall rethrown by getServiceToscaModel once javax client throw exception ");
67     }
68
69 }