Best Mockito code snippet using org.mockito.Mockito.request
Source:TestMainClientExec.java
...89import org.mockito.stubbing.Answer;90@SuppressWarnings({"boxing","static-access"}) // test code91public class TestMainClientExec {92 @Mock93 private HttpRequestExecutor requestExecutor;94 @Mock95 private HttpClientConnectionManager connManager;96 @Mock97 private ConnectionReuseStrategy reuseStrategy;98 @Mock99 private ConnectionKeepAliveStrategy keepAliveStrategy;100 @Mock101 private HttpProcessor proxyHttpProcessor;102 @Mock103 private AuthenticationStrategy targetAuthStrategy;104 @Mock105 private AuthenticationStrategy proxyAuthStrategy;106 @Mock107 private UserTokenHandler userTokenHandler;108 @Mock109 private HttpExecutionAware execAware;110 @Mock111 private ConnectionRequest connRequest;112 @Mock113 private HttpClientConnection managedConn;114 private MainClientExec mainClientExec;115 private HttpHost target;116 private HttpHost proxy;117 @Before118 public void setup() throws Exception {119 MockitoAnnotations.initMocks(this);120 mainClientExec = new MainClientExec(requestExecutor, connManager, reuseStrategy,121 keepAliveStrategy, proxyHttpProcessor, targetAuthStrategy, proxyAuthStrategy, userTokenHandler);122 target = new HttpHost("foo", 80);123 proxy = new HttpHost("bar", 8888);124 Mockito.when(connManager.requestConnection(125 Mockito.<HttpRoute>any(), Mockito.any())).thenReturn(connRequest);126 Mockito.when(connRequest.get(127 Mockito.anyLong(), Mockito.<TimeUnit>any())).thenReturn(managedConn);128 final Map<String, Header> challenges = new HashMap<String, Header>();129 challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=test"));130 final AuthOption authOption = new AuthOption(131 new BasicScheme(), new UsernamePasswordCredentials("user:pass"));132 Mockito.when(targetAuthStrategy.getChallenges(133 Mockito.eq(target),134 Mockito.<HttpResponse>any(),135 Mockito.<HttpClientContext>any())).thenReturn(challenges);136 Mockito.when(targetAuthStrategy.getChallenges(137 Mockito.eq(target),138 Mockito.<HttpResponse>any(),139 Mockito.<HttpClientContext>any())).thenReturn(challenges);140 Mockito.when(targetAuthStrategy.select(141 Mockito.same(challenges),142 Mockito.eq(target),143 Mockito.<HttpResponse>any(),144 Mockito.<HttpClientContext>any())).thenReturn(145 new LinkedList<AuthOption>(Arrays.asList(authOption)));146 Mockito.when(proxyAuthStrategy.getChallenges(147 Mockito.eq(proxy),148 Mockito.<HttpResponse>any(),149 Mockito.<HttpClientContext>any())).thenReturn(challenges);150 Mockito.when(proxyAuthStrategy.getChallenges(151 Mockito.eq(proxy),152 Mockito.<HttpResponse>any(),153 Mockito.<HttpClientContext>any())).thenReturn(challenges);154 Mockito.when(proxyAuthStrategy.select(155 Mockito.same(challenges),156 Mockito.eq(proxy),157 Mockito.<HttpResponse>any(),158 Mockito.<HttpClientContext>any())).thenReturn(159 new LinkedList<AuthOption>(Arrays.asList(authOption)));160 }161 @Test162 public void testExecRequestNonPersistentConnection() throws Exception {163 final HttpRoute route = new HttpRoute(target);164 final HttpClientContext context = new HttpClientContext();165 final RequestConfig config = RequestConfig.custom()166 .setConnectTimeout(123)167 .setSocketTimeout(234)168 .setConnectionRequestTimeout(345)169 .build();170 context.setRequestConfig(config);171 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));172 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");173 Mockito.when(requestExecutor.execute(174 Mockito.same(request),175 Mockito.<HttpClientConnection>any(),176 Mockito.<HttpClientContext>any())).thenReturn(response);177 final CloseableHttpResponse finalResponse = mainClientExec.execute(178 route, request, context, execAware);179 Mockito.verify(connManager).requestConnection(route, null);180 Mockito.verify(connRequest).get(345, TimeUnit.MILLISECONDS);181 Mockito.verify(execAware, Mockito.times(1)).setCancellable(connRequest);182 Mockito.verify(execAware, Mockito.times(2)).setCancellable(Mockito.<Cancellable>any());183 Mockito.verify(connManager).connect(managedConn, route, 123, context);184 Mockito.verify(connManager).routeComplete(managedConn, route, context);185 Mockito.verify(managedConn).setSocketTimeout(234);186 Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context);187 Mockito.verify(managedConn, Mockito.times(1)).close();188 Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS);189 Assert.assertNotNull(context.getTargetAuthState());190 Assert.assertNotNull(context.getProxyAuthState());191 Assert.assertSame(managedConn, context.getConnection());192 Assert.assertNull(context.getUserToken());193 Assert.assertNotNull(finalResponse);194 Assert.assertTrue(finalResponse instanceof HttpResponseProxy);195 }196 @Test197 public void testExecRequestPersistentConnection() throws Exception {198 final HttpRoute route = new HttpRoute(target);199 final HttpClientContext context = new HttpClientContext();200 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));201 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");202 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);203 Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);204 Mockito.when(requestExecutor.execute(205 Mockito.same(request),206 Mockito.<HttpClientConnection>any(),207 Mockito.<HttpClientContext>any())).thenReturn(response);208 Mockito.when(reuseStrategy.keepAlive(209 Mockito.same(response),210 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);211 Mockito.when(keepAliveStrategy.getKeepAliveDuration(212 Mockito.same(response),213 Mockito.<HttpClientContext>any())).thenReturn(678L);214 final CloseableHttpResponse finalResponse = mainClientExec.execute(215 route, request, context, execAware);216 Mockito.verify(connManager).requestConnection(route, null);217 Mockito.verify(connRequest).get(0, TimeUnit.MILLISECONDS);218 Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context);219 Mockito.verify(connManager).releaseConnection(managedConn, null, 678L, TimeUnit.MILLISECONDS);220 Mockito.verify(managedConn, Mockito.never()).close();221 Assert.assertNotNull(finalResponse);222 Assert.assertTrue(finalResponse instanceof HttpResponseProxy);223 }224 @Test225 public void testExecRequestPersistentStatefulConnection() throws Exception {226 final HttpRoute route = new HttpRoute(target);227 final HttpClientContext context = new HttpClientContext();228 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));229 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");230 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);231 Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);232 Mockito.when(requestExecutor.execute(233 Mockito.same(request),234 Mockito.<HttpClientConnection>any(),235 Mockito.<HttpClientContext>any())).thenReturn(response);236 Mockito.when(reuseStrategy.keepAlive(237 Mockito.same(response),238 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);239 Mockito.when(userTokenHandler.getUserToken(240 Mockito.<HttpClientContext>any())).thenReturn("this and that");241 mainClientExec.execute(route, request, context, execAware);242 Mockito.verify(connManager).requestConnection(route, null);243 Mockito.verify(connRequest).get(0, TimeUnit.MILLISECONDS);244 Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context);245 Mockito.verify(connManager).releaseConnection(managedConn, "this and that", 0, TimeUnit.MILLISECONDS);246 Mockito.verify(managedConn, Mockito.never()).close();247 Assert.assertEquals("this and that", context.getUserToken());248 }249 @Test250 public void testExecRequestConnectionRelease() throws Exception {251 final HttpRoute route = new HttpRoute(target);252 final HttpClientContext context = new HttpClientContext();253 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));254 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");255 // The entity is streaming256 response.setEntity(EntityBuilder.create()257 .setStream(new ByteArrayInputStream(new byte[]{}))258 .build());259 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);260 Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);261 Mockito.when(requestExecutor.execute(262 Mockito.same(request),263 Mockito.<HttpClientConnection>any(),264 Mockito.<HttpClientContext>any())).thenReturn(response);265 Mockito.when(reuseStrategy.keepAlive(266 Mockito.same(response),267 Mockito.<HttpClientContext>any())).thenReturn(Boolean.FALSE);268 final CloseableHttpResponse finalResponse = mainClientExec.execute(269 route, request, context, execAware);270 Mockito.verify(connManager).requestConnection(route, null);271 Mockito.verify(connRequest).get(0, TimeUnit.MILLISECONDS);272 Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context);273 Mockito.verify(connManager, Mockito.never()).releaseConnection(274 Mockito.same(managedConn),275 Mockito.any(),276 Mockito.anyInt(),277 Mockito.<TimeUnit>any());278 Mockito.verify(managedConn, Mockito.never()).close();279 Assert.assertNotNull(finalResponse);280 Assert.assertTrue(finalResponse instanceof HttpResponseProxy);281 finalResponse.close();282 Mockito.verify(connManager, Mockito.times(1)).releaseConnection(283 managedConn, null, 0, TimeUnit.MILLISECONDS);284 Mockito.verify(managedConn, Mockito.times(1)).close();285 }286 @Test287 public void testSocketTimeoutExistingConnection() throws Exception {288 final HttpRoute route = new HttpRoute(target);289 final HttpClientContext context = new HttpClientContext();290 final RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).build();291 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));292 context.setRequestConfig(config);293 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");294 Mockito.when(managedConn.isOpen()).thenReturn(true);295 Mockito.when(requestExecutor.execute(296 Mockito.same(request),297 Mockito.<HttpClientConnection>any(),298 Mockito.<HttpClientContext>any())).thenReturn(response);299 mainClientExec.execute(route, request, context, execAware);300 Mockito.verify(managedConn).setSocketTimeout(3000);301 }302 @Test303 public void testSocketTimeoutReset() throws Exception {304 final HttpRoute route = new HttpRoute(target);305 final HttpClientContext context = new HttpClientContext();306 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));307 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");308 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);309 Mockito.when(requestExecutor.execute(310 Mockito.same(request),311 Mockito.<HttpClientConnection>any(),312 Mockito.<HttpClientContext>any())).thenReturn(response);313 mainClientExec.execute(route, request, context, execAware);314 Mockito.verify(managedConn, Mockito.never()).setSocketTimeout(Mockito.anyInt());315 }316 @Test(expected=RequestAbortedException.class)317 public void testExecAbortedPriorToConnectionLease() throws Exception {318 final HttpRoute route = new HttpRoute(target);319 final HttpClientContext context = new HttpClientContext();320 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));321 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.FALSE);322 Mockito.when(execAware.isAborted()).thenReturn(Boolean.TRUE);323 try {324 mainClientExec.execute(route, request, context, execAware);325 } catch (final IOException ex) {326 Mockito.verify(connRequest, Mockito.times(1)).cancel();327 throw ex;328 }329 }330 @Test(expected=RequestAbortedException.class)331 public void testExecAbortedPriorToConnectionSetup() throws Exception {332 final HttpRoute route = new HttpRoute(target);333 final HttpClientContext context = new HttpClientContext();334 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));335 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.FALSE);336 Mockito.when(execAware.isAborted()).thenReturn(Boolean.FALSE, Boolean.TRUE);337 try {338 mainClientExec.execute(route, request, context, execAware);339 } catch (final IOException ex) {340 Mockito.verify(connRequest, Mockito.times(1)).get(0, TimeUnit.MILLISECONDS);341 Mockito.verify(execAware, Mockito.times(2)).setCancellable(Mockito.<Cancellable>any());342 Mockito.verify(connManager, Mockito.never()).connect(343 Mockito.same(managedConn),344 Mockito.<HttpRoute>any(),345 Mockito.anyInt(),346 Mockito.<HttpContext>any());347 throw ex;348 }349 }350 @Test(expected=RequestAbortedException.class)351 public void testExecAbortedPriorToRequestExecution() throws Exception {352 final HttpRoute route = new HttpRoute(target);353 final HttpClientContext context = new HttpClientContext();354 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));355 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.FALSE);356 Mockito.when(execAware.isAborted()).thenReturn(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE);357 try {358 mainClientExec.execute(route, request, context, execAware);359 } catch (final IOException ex) {360 Mockito.verify(connRequest, Mockito.times(1)).get(0, TimeUnit.MILLISECONDS);361 Mockito.verify(connManager, Mockito.times(1)).connect(managedConn, route, 0, context);362 Mockito.verify(requestExecutor, Mockito.never()).execute(363 Mockito.same(request),364 Mockito.<HttpClientConnection>any(),365 Mockito.<HttpClientContext>any());366 throw ex;367 }368 }369 @Test(expected=RequestAbortedException.class)370 public void testExecConnectionRequestFailed() throws Exception {371 final HttpRoute route = new HttpRoute(target);372 final HttpClientContext context = new HttpClientContext();373 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));374 Mockito.when(connRequest.get(Mockito.anyInt(), Mockito.<TimeUnit>any()))375 .thenThrow(new ExecutionException("Opppsie", null));376 mainClientExec.execute(route, request, context, execAware);377 }378 @Test379 public void testExecRequestRetryOnAuthChallenge() throws Exception {380 final HttpRoute route = new HttpRoute(target);381 final HttpClientContext context = new HttpClientContext();382 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));383 final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");384 final InputStream inStream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));385 response1.setEntity(EntityBuilder.create()386 .setStream(inStream1)387 .build());388 final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");389 final InputStream inStream2 = Mockito.spy(new ByteArrayInputStream(new byte[] {2, 3, 4}));390 response2.setEntity(EntityBuilder.create()391 .setStream(inStream2)392 .build());393 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);394 Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);395 Mockito.when(requestExecutor.execute(396 Mockito.same(request),397 Mockito.<HttpClientConnection>any(),398 Mockito.<HttpClientContext>any())).thenReturn(response1, response2);399 Mockito.when(reuseStrategy.keepAlive(400 Mockito.<HttpResponse>any(),401 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);402 Mockito.when(targetAuthStrategy.isAuthenticationRequested(403 Mockito.eq(target),404 Mockito.same(response1),405 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);406 final CloseableHttpResponse finalResponse = mainClientExec.execute(407 route, request, context, execAware);408 Mockito.verify(requestExecutor, Mockito.times(2)).execute(request, managedConn, context);409 Mockito.verify(inStream1).close();410 Mockito.verify(inStream2, Mockito.never()).close();411 Assert.assertNotNull(finalResponse);412 Assert.assertEquals(200, finalResponse.getStatusLine().getStatusCode());413 }414 @Test415 public void testExecEntityEnclosingRequestRetryOnAuthChallenge() throws Exception {416 final HttpRoute route = new HttpRoute(target);417 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));418 final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");419 final InputStream inStream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));420 response1.setEntity(EntityBuilder.create()421 .setStream(inStream1)422 .build());423 final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");424 final InputStream inStream2 = Mockito.spy(new ByteArrayInputStream(new byte[] {2, 3, 4}));425 response2.setEntity(EntityBuilder.create()426 .setStream(inStream2)427 .build());428 final AuthState proxyAuthState = new AuthState();429 proxyAuthState.setState(AuthProtocolState.SUCCESS);430 proxyAuthState.update(new NTLMScheme(), new NTCredentials("user:pass"));431 final HttpClientContext context = new HttpClientContext();432 context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState);433 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);434 Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);435 Mockito.when(requestExecutor.execute(436 Mockito.same(request),437 Mockito.<HttpClientConnection>any(),438 Mockito.<HttpClientContext>any())).thenReturn(response1, response2);439 Mockito.when(reuseStrategy.keepAlive(440 Mockito.<HttpResponse>any(),441 Mockito.<HttpClientContext>any())).thenReturn(Boolean.FALSE);442 Mockito.when(targetAuthStrategy.isAuthenticationRequested(443 Mockito.eq(target),444 Mockito.same(response1),445 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);446 final CloseableHttpResponse finalResponse = mainClientExec.execute(447 route, request, context, execAware);448 Mockito.verify(requestExecutor, Mockito.times(2)).execute(request, managedConn, context);449 Mockito.verify(managedConn).close();450 Mockito.verify(inStream2, Mockito.never()).close();451 Assert.assertNotNull(finalResponse);452 Assert.assertEquals(200, finalResponse.getStatusLine().getStatusCode());453 Assert.assertNull(proxyAuthState.getAuthScheme());454 Assert.assertNull(proxyAuthState.getCredentials());455 }456 @Test(expected = NonRepeatableRequestException.class)457 public void testExecEntityEnclosingRequest() throws Exception {458 final HttpRoute route = new HttpRoute(target);459 final HttpClientContext context = new HttpClientContext();460 final HttpPost post = new HttpPost("http://bar/test");461 final InputStream inStream0 = new ByteArrayInputStream(new byte[] {1, 2, 3});462 post.setEntity(EntityBuilder.create()463 .setStream(inStream0)464 .build());465 final HttpRequestWrapper request = HttpRequestWrapper.wrap(post);466 final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");467 final InputStream inStream1 = new ByteArrayInputStream(new byte[] {1, 2, 3});468 response1.setEntity(EntityBuilder.create()469 .setStream(inStream1)470 .build());471 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);472 Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);473 Mockito.when(requestExecutor.execute(474 Mockito.same(request),475 Mockito.<HttpClientConnection>any(),476 Mockito.<HttpClientContext>any())).thenAnswer(new Answer<HttpResponse>() {477 @Override478 public HttpResponse answer(final InvocationOnMock invocationOnMock) throws Throwable {479 final Object[] args = invocationOnMock.getArguments();480 final HttpEntityEnclosingRequest requestEE = (HttpEntityEnclosingRequest) args[0];481 requestEE.getEntity().writeTo(new ByteArrayOutputStream());482 return response1;483 }484 });485 Mockito.when(reuseStrategy.keepAlive(486 Mockito.<HttpResponse>any(),487 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);488 Mockito.when(targetAuthStrategy.isAuthenticationRequested(489 Mockito.eq(target),490 Mockito.same(response1),491 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);492 mainClientExec.execute(route, request, context, execAware);493 }494 @Test(expected=InterruptedIOException.class)495 public void testExecConnectionShutDown() throws Exception {496 final HttpRoute route = new HttpRoute(target);497 final HttpClientContext context = new HttpClientContext();498 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));499 Mockito.when(requestExecutor.execute(500 Mockito.<HttpRequest>any(),501 Mockito.<HttpClientConnection>any(),502 Mockito.<HttpClientContext>any())).thenThrow(new ConnectionShutdownException());503 mainClientExec.execute(route, request, context, execAware);504 }505 @Test(expected=RuntimeException.class)506 public void testExecRuntimeException() throws Exception {507 final HttpRoute route = new HttpRoute(target);508 final HttpClientContext context = new HttpClientContext();509 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));510 Mockito.when(requestExecutor.execute(511 Mockito.<HttpRequest>any(),512 Mockito.<HttpClientConnection>any(),513 Mockito.<HttpClientContext>any())).thenThrow(new RuntimeException("Ka-boom"));514 try {515 mainClientExec.execute(route, request, context, execAware);516 } catch (final Exception ex) {517 Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS);518 throw ex;519 }520 }521 @Test(expected=HttpException.class)522 public void testExecHttpException() throws Exception {523 final HttpRoute route = new HttpRoute(target);524 final HttpClientContext context = new HttpClientContext();525 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));526 Mockito.when(requestExecutor.execute(527 Mockito.<HttpRequest>any(),528 Mockito.<HttpClientConnection>any(),529 Mockito.<HttpClientContext>any())).thenThrow(new HttpException("Ka-boom"));530 try {531 mainClientExec.execute(route, request, context, execAware);532 } catch (final Exception ex) {533 Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS);534 throw ex;535 }536 }537 @Test(expected=IOException.class)538 public void testExecIOException() throws Exception {539 final HttpRoute route = new HttpRoute(target);540 final HttpClientContext context = new HttpClientContext();541 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));542 Mockito.when(requestExecutor.execute(543 Mockito.<HttpRequest>any(),544 Mockito.<HttpClientConnection>any(),545 Mockito.<HttpClientContext>any())).thenThrow(new IOException("Ka-boom"));546 try {547 mainClientExec.execute(route, request, context, execAware);548 } catch (final Exception ex) {549 Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS);550 throw ex;551 }552 }553 @Test554 public void testEstablishDirectRoute() throws Exception {555 final AuthState authState = new AuthState();556 final HttpRoute route = new HttpRoute(target);557 final HttpClientContext context = new HttpClientContext();558 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));559 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);560 mainClientExec.establishRoute(authState, managedConn, route, request, context);561 Mockito.verify(connManager).connect(managedConn, route, 0, context);562 Mockito.verify(connManager).routeComplete(managedConn, route, context);563 }564 @Test565 public void testEstablishRouteDirectProxy() throws Exception {566 final AuthState authState = new AuthState();567 final HttpRoute route = new HttpRoute(target, null, proxy, false);568 final HttpClientContext context = new HttpClientContext();569 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));570 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);571 mainClientExec.establishRoute(authState, managedConn, route, request, context);572 Mockito.verify(connManager).connect(managedConn, route, 0, context);573 Mockito.verify(connManager).routeComplete(managedConn, route, context);574 }575 @Test576 public void testEstablishRouteViaProxyTunnel() throws Exception {577 final AuthState authState = new AuthState();578 final HttpRoute route = new HttpRoute(target, null, proxy, true);579 final HttpClientContext context = new HttpClientContext();580 final RequestConfig config = RequestConfig.custom()581 .setConnectTimeout(321)582 .build();583 context.setRequestConfig(config);584 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));585 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");586 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);587 Mockito.when(requestExecutor.execute(588 Mockito.<HttpRequest>any(),589 Mockito.<HttpClientConnection>any(),590 Mockito.<HttpClientContext>any())).thenReturn(response);591 mainClientExec.establishRoute(authState, managedConn, route, request, context);592 Mockito.verify(connManager).connect(managedConn, route, 321, context);593 Mockito.verify(connManager).routeComplete(managedConn, route, context);594 final ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);595 Mockito.verify(requestExecutor).execute(596 reqCaptor.capture(),597 Mockito.same(managedConn),598 Mockito.same(context));599 final HttpRequest connect = reqCaptor.getValue();600 Assert.assertNotNull(connect);601 Assert.assertEquals("CONNECT", connect.getRequestLine().getMethod());602 Assert.assertEquals(HttpVersion.HTTP_1_1, connect.getRequestLine().getProtocolVersion());603 Assert.assertEquals("foo:80", connect.getRequestLine().getUri());604 }605 @Test(expected = HttpException.class)606 public void testEstablishRouteViaProxyTunnelUnexpectedResponse() throws Exception {607 final AuthState authState = new AuthState();608 final HttpRoute route = new HttpRoute(target, null, proxy, true);609 final HttpClientContext context = new HttpClientContext();610 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));611 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 101, "Lost");612 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);613 Mockito.when(requestExecutor.execute(614 Mockito.<HttpRequest>any(),615 Mockito.<HttpClientConnection>any(),616 Mockito.<HttpClientContext>any())).thenReturn(response);617 mainClientExec.establishRoute(authState, managedConn, route, request, context);618 }619 @Test(expected = HttpException.class)620 public void testEstablishRouteViaProxyTunnelFailure() throws Exception {621 final AuthState authState = new AuthState();622 final HttpRoute route = new HttpRoute(target, null, proxy, true);623 final HttpClientContext context = new HttpClientContext();624 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));625 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 500, "Boom");626 response.setEntity(new StringEntity("Ka-boom"));627 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);628 Mockito.when(requestExecutor.execute(629 Mockito.<HttpRequest>any(),630 Mockito.<HttpClientConnection>any(),631 Mockito.<HttpClientContext>any())).thenReturn(response);632 try {633 mainClientExec.establishRoute(authState, managedConn, route, request, context);634 } catch (final TunnelRefusedException ex) {635 final HttpResponse r = ex.getResponse();636 Assert.assertEquals("Ka-boom", EntityUtils.toString(r.getEntity()));637 Mockito.verify(managedConn).close();638 throw ex;639 }640 }641 @Test642 public void testEstablishRouteViaProxyTunnelRetryOnAuthChallengePersistentConnection() throws Exception {643 final AuthState authState = new AuthState();644 final HttpRoute route = new HttpRoute(target, null, proxy, true);645 final HttpClientContext context = new HttpClientContext();646 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));647 final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");648 final InputStream inStream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));649 response1.setEntity(EntityBuilder.create()650 .setStream(inStream1)651 .build());652 final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");653 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);654 Mockito.when(proxyAuthStrategy.isAuthenticationRequested(655 Mockito.eq(proxy),656 Mockito.same(response1),657 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);658 Mockito.when(reuseStrategy.keepAlive(659 Mockito.<HttpResponse>any(),660 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);661 Mockito.when(requestExecutor.execute(662 Mockito.<HttpRequest>any(),663 Mockito.<HttpClientConnection>any(),664 Mockito.<HttpClientContext>any())).thenReturn(response1, response2);665 mainClientExec.establishRoute(authState, managedConn, route, request, context);666 Mockito.verify(connManager).connect(managedConn, route, 0, context);667 Mockito.verify(connManager).routeComplete(managedConn, route, context);668 Mockito.verify(inStream1).close();669 }670 @Test671 public void testEstablishRouteViaProxyTunnelRetryOnAuthChallengeNonPersistentConnection() throws Exception {672 final AuthState authState = new AuthState();673 final HttpRoute route = new HttpRoute(target, null, proxy, true);674 final HttpClientContext context = new HttpClientContext();675 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));676 final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");677 final InputStream inStream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));678 response1.setEntity(EntityBuilder.create()679 .setStream(inStream1)680 .build());681 final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");682 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);683 Mockito.when(proxyAuthStrategy.isAuthenticationRequested(684 Mockito.eq(proxy),685 Mockito.same(response1),686 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);687 Mockito.when(reuseStrategy.keepAlive(688 Mockito.<HttpResponse>any(),689 Mockito.<HttpClientContext>any())).thenReturn(Boolean.FALSE);690 Mockito.when(requestExecutor.execute(691 Mockito.<HttpRequest>any(),692 Mockito.<HttpClientConnection>any(),693 Mockito.<HttpClientContext>any())).thenReturn(response1, response2);694 mainClientExec.establishRoute(authState, managedConn, route, request, context);695 Mockito.verify(connManager).connect(managedConn, route, 0, context);696 Mockito.verify(connManager).routeComplete(managedConn, route, context);697 Mockito.verify(inStream1, Mockito.never()).close();698 Mockito.verify(managedConn).close();699 }700 @Test(expected = HttpException.class)701 public void testEstablishRouteViaProxyTunnelMultipleHops() throws Exception {702 final AuthState authState = new AuthState();703 final HttpHost proxy1 = new HttpHost("this", 8888);704 final HttpHost proxy2 = new HttpHost("that", 8888);705 final HttpRoute route = new HttpRoute(target, null, new HttpHost[] {proxy1, proxy2},706 true, RouteInfo.TunnelType.TUNNELLED, RouteInfo.LayerType.LAYERED);707 final HttpClientContext context = new HttpClientContext();708 final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));709 Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);710 mainClientExec.establishRoute(authState, managedConn, route, request, context);711 }712}...
Source:TestRedirectExec.java
...63import java.util.List;64@SuppressWarnings({"boxing","static-access"}) // test code65public class TestRedirectExec {66 @Mock67 private ClientExecChain requestExecutor;68 @Mock69 private HttpRoutePlanner httpRoutePlanner;70 @Mock71 private RedirectStrategy redirectStrategy;72 @Mock73 private HttpExecutionAware execAware;74 private RedirectExec redirectExec;75 private HttpHost target;76 @Before77 public void setup() throws Exception {78 MockitoAnnotations.initMocks(this);79 redirectExec = new RedirectExec(requestExecutor, httpRoutePlanner, redirectStrategy);80 target = new HttpHost("localhost", 80);81 }82 @Test83 public void testFundamentals() throws Exception {84 final HttpRoute route = new HttpRoute(target);85 final HttpGet get = new HttpGet("/test");86 get.addHeader("header", "this");87 get.addHeader("header", "that");88 final HttpRequestWrapper request = HttpRequestWrapper.wrap(get);89 final HttpClientContext context = HttpClientContext.create();90 final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class);91 final InputStream inStream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));92 final HttpEntity entity1 = EntityBuilder.create()93 .setStream(inStream1)94 .build();95 Mockito.when(response1.getEntity()).thenReturn(entity1);96 final CloseableHttpResponse response2 = Mockito.mock(CloseableHttpResponse.class);97 final InputStream inStream2 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));98 final HttpEntity entity2 = EntityBuilder.create()99 .setStream(inStream2)100 .build();101 Mockito.when(response2.getEntity()).thenReturn(entity2);102 final HttpGet redirect = new HttpGet("http://localhost:80/redirect");103 Mockito.when(requestExecutor.execute(104 Mockito.eq(route),105 Mockito.same(request),106 Mockito.<HttpClientContext>any(),107 Mockito.<HttpExecutionAware>any())).thenReturn(response1);108 Mockito.when(requestExecutor.execute(109 Mockito.eq(route),110 HttpRequestWrapperMatcher.same(redirect),111 Mockito.<HttpClientContext>any(),112 Mockito.<HttpExecutionAware>any())).thenReturn(response2);113 Mockito.when(redirectStrategy.isRedirected(114 Mockito.same(get),115 Mockito.same(response1),116 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);117 Mockito.when(redirectStrategy.getRedirect(118 Mockito.same(get),119 Mockito.same(response1),120 Mockito.<HttpClientContext>any())).thenReturn(redirect);121 Mockito.when(httpRoutePlanner.determineRoute(122 Mockito.eq(target),123 Mockito.<HttpRequestWrapper>any(),124 Mockito.<HttpClientContext>any())).thenReturn(route);125 redirectExec.execute(route, request, context, execAware);126 final ArgumentCaptor<HttpRequestWrapper> reqCaptor = ArgumentCaptor.forClass(127 HttpRequestWrapper.class);128 Mockito.verify(requestExecutor, Mockito.times(2)).execute(129 Mockito.eq(route),130 reqCaptor.capture(),131 Mockito.same(context),132 Mockito.same(execAware));133 final List<HttpRequestWrapper> allValues = reqCaptor.getAllValues();134 Assert.assertNotNull(allValues);135 Assert.assertEquals(2, allValues.size());136 Assert.assertSame(request, allValues.get(0));137 final HttpRequestWrapper redirectWrapper = allValues.get(1);138 final Header[] headers = redirectWrapper.getHeaders("header");139 Assert.assertNotNull(headers);140 Assert.assertEquals(2, headers.length);141 Assert.assertEquals("this", headers[0].getValue());142 Assert.assertEquals("that", headers[1].getValue());143 Mockito.verify(response1, Mockito.times(1)).close();144 Mockito.verify(inStream1, Mockito.times(1)).close();145 Mockito.verify(response2, Mockito.never()).close();146 Mockito.verify(inStream2, Mockito.never()).close();147 }148 @Test(expected = RedirectException.class)149 public void testMaxRedirect() throws Exception {150 final HttpRoute route = new HttpRoute(target);151 final HttpGet get = new HttpGet("/test");152 final HttpRequestWrapper request = HttpRequestWrapper.wrap(get);153 final HttpClientContext context = HttpClientContext.create();154 final RequestConfig config = RequestConfig.custom()155 .setRedirectsEnabled(true)156 .setMaxRedirects(3)157 .build();158 context.setRequestConfig(config);159 final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class);160 final HttpGet redirect = new HttpGet("http://localhost:80/redirect");161 Mockito.when(requestExecutor.execute(162 Mockito.eq(route),163 Mockito.<HttpRequestWrapper>any(),164 Mockito.<HttpClientContext>any(),165 Mockito.<HttpExecutionAware>any())).thenReturn(response1);166 Mockito.when(redirectStrategy.isRedirected(167 Mockito.<HttpRequestWrapper>any(),168 Mockito.<HttpResponse>any(),169 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);170 Mockito.when(redirectStrategy.getRedirect(171 Mockito.<HttpRequestWrapper>any(),172 Mockito.<HttpResponse>any(),173 Mockito.<HttpClientContext>any())).thenReturn(redirect);174 Mockito.when(httpRoutePlanner.determineRoute(175 Mockito.eq(target),176 Mockito.<HttpRequestWrapper>any(),177 Mockito.<HttpClientContext>any())).thenReturn(route);178 redirectExec.execute(route, request, context, execAware);179 }180 @Test(expected = HttpException.class)181 public void testRelativeRedirect() throws Exception {182 final HttpRoute route = new HttpRoute(target);183 final HttpGet get = new HttpGet("/test");184 final HttpRequestWrapper request = HttpRequestWrapper.wrap(get);185 final HttpClientContext context = HttpClientContext.create();186 final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class);187 final CloseableHttpResponse response2 = Mockito.mock(CloseableHttpResponse.class);188 final HttpGet redirect = new HttpGet("/redirect");189 Mockito.when(requestExecutor.execute(190 Mockito.eq(route),191 Mockito.same(request),192 Mockito.<HttpClientContext>any(),193 Mockito.<HttpExecutionAware>any())).thenReturn(response1);194 Mockito.when(requestExecutor.execute(195 Mockito.eq(route),196 HttpRequestWrapperMatcher.same(redirect),197 Mockito.<HttpClientContext>any(),198 Mockito.<HttpExecutionAware>any())).thenReturn(response2);199 Mockito.when(redirectStrategy.isRedirected(200 Mockito.same(get),201 Mockito.same(response1),202 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);203 Mockito.when(redirectStrategy.getRedirect(204 Mockito.same(get),205 Mockito.same(response1),206 Mockito.<HttpClientContext>any())).thenReturn(redirect);207 Mockito.when(httpRoutePlanner.determineRoute(208 Mockito.eq(target),209 Mockito.<HttpRequestWrapper>any(),210 Mockito.<HttpClientContext>any())).thenReturn(route);211 redirectExec.execute(route, request, context, execAware);212 }213 @Test214 public void testCrossSiteRedirect() throws Exception {215 final HttpRoute route = new HttpRoute(target);216 final HttpGet get = new HttpGet("/test");217 final HttpRequestWrapper request = HttpRequestWrapper.wrap(get);218 final HttpClientContext context = HttpClientContext.create();219 final AuthState targetAuthState = new AuthState();220 targetAuthState.setState(AuthProtocolState.SUCCESS);221 targetAuthState.update(new BasicScheme(), new UsernamePasswordCredentials("user", "pass"));222 final AuthState proxyAuthState = new AuthState();223 proxyAuthState.setState(AuthProtocolState.SUCCESS);224 proxyAuthState.update(new NTLMScheme(), new NTCredentials("user", "pass", null, null));225 context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState);226 context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState);227 final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class);228 final CloseableHttpResponse response2 = Mockito.mock(CloseableHttpResponse.class);229 final HttpGet redirect = new HttpGet("http://otherhost/redirect");230 Mockito.when(requestExecutor.execute(231 Mockito.eq(route),232 Mockito.same(request),233 Mockito.<HttpClientContext>any(),234 Mockito.<HttpExecutionAware>any())).thenReturn(response1);235 Mockito.when(requestExecutor.execute(236 Mockito.eq(route),237 HttpRequestWrapperMatcher.same(redirect),238 Mockito.<HttpClientContext>any(),239 Mockito.<HttpExecutionAware>any())).thenReturn(response2);240 Mockito.when(redirectStrategy.isRedirected(241 Mockito.same(get),242 Mockito.same(response1),243 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);244 Mockito.when(redirectStrategy.getRedirect(245 Mockito.same(get),246 Mockito.same(response1),247 Mockito.<HttpClientContext>any())).thenReturn(redirect);248 Mockito.when(httpRoutePlanner.determineRoute(249 Mockito.eq(target),250 Mockito.<HttpRequestWrapper>any(),251 Mockito.<HttpClientContext>any())).thenReturn(new HttpRoute(new HttpHost("otherhost", 80)));252 redirectExec.execute(route, request, context, execAware);253 Assert.assertNotNull(context.getTargetAuthState());254 Assert.assertEquals(AuthProtocolState.UNCHALLENGED, context.getTargetAuthState().getState());255 Assert.assertEquals(null, context.getTargetAuthState().getAuthScheme());256 Assert.assertNotNull(context.getProxyAuthState());257 Assert.assertEquals(AuthProtocolState.UNCHALLENGED, context.getProxyAuthState().getState());258 Assert.assertEquals(null, context.getProxyAuthState().getAuthScheme());259 }260 @Test(expected = RuntimeException.class)261 public void testRedirectRuntimeException() throws Exception {262 final HttpRoute route = new HttpRoute(target);263 final HttpGet get = new HttpGet("/test");264 final HttpRequestWrapper request = HttpRequestWrapper.wrap(get);265 final HttpClientContext context = HttpClientContext.create();266 final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class);267 Mockito.when(requestExecutor.execute(268 Mockito.eq(route),269 Mockito.same(request),270 Mockito.<HttpClientContext>any(),271 Mockito.<HttpExecutionAware>any())).thenReturn(response1);272 Mockito.when(redirectStrategy.isRedirected(273 Mockito.same(request),274 Mockito.same(response1),275 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);276 Mockito.doThrow(new RuntimeException("Oppsie")).when(redirectStrategy.getRedirect(277 Mockito.same(request),278 Mockito.same(response1),279 Mockito.<HttpClientContext>any()));280 try {281 redirectExec.execute(route, request, context, execAware);282 } catch (final Exception ex) {283 Mockito.verify(response1).close();284 throw ex;285 }286 }287 @Test(expected = ProtocolException.class)288 public void testRedirectProtocolException() throws Exception {289 final HttpRoute route = new HttpRoute(target);290 final HttpGet get = new HttpGet("/test");291 final HttpRequestWrapper request = HttpRequestWrapper.wrap(get);292 final HttpClientContext context = HttpClientContext.create();293 final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class);294 final InputStream inStream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));295 final HttpEntity entity1 = EntityBuilder.create()296 .setStream(inStream1)297 .build();298 Mockito.when(response1.getEntity()).thenReturn(entity1);299 Mockito.when(requestExecutor.execute(300 Mockito.eq(route),301 Mockito.same(request),302 Mockito.<HttpClientContext>any(),303 Mockito.<HttpExecutionAware>any())).thenReturn(response1);304 Mockito.when(redirectStrategy.isRedirected(305 Mockito.same(get),306 Mockito.same(response1),307 Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);308 Mockito.doThrow(new ProtocolException("Oppsie")).when(redirectStrategy).getRedirect(309 Mockito.same(get),310 Mockito.same(response1),311 Mockito.<HttpClientContext>any());312 try {313 redirectExec.execute(route, request, context, execAware);314 } catch (final Exception ex) {315 Mockito.verify(inStream1).close();316 Mockito.verify(response1).close();317 throw ex;318 }319 }320 static class HttpRequestWrapperMatcher extends ArgumentMatcher<HttpRequestWrapper> {321 private final HttpRequest original;322 HttpRequestWrapperMatcher(final HttpRequest original) {323 super();324 this.original = original;325 }326 @Override327 public boolean matches(final Object obj) {...
Source:TestDelegationTokenAuthenticationHandlerWithMocks.java
...56 public void destroy() {57 }58 @Override59 public boolean managementOperation(AuthenticationToken token,60 HttpServletRequest request, HttpServletResponse response)61 throws IOException, AuthenticationException {62 return false;63 }64 @Override65 public AuthenticationToken authenticate(HttpServletRequest request,66 HttpServletResponse response)67 throws IOException, AuthenticationException {68 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);69 response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, "mock");70 return null;71 }72 });73 }74 }75 private DelegationTokenAuthenticationHandler handler;76 @Before77 public void setUp() throws Exception {78 Properties conf = new Properties();79 conf.put(KerberosDelegationTokenAuthenticationHandler.TOKEN_KIND, "foo");80 handler = new MockDelegationTokenAuthenticationHandler();81 handler.initTokenManager(conf);82 }83 @After84 public void cleanUp() {85 handler.destroy();86 }87 @Test88 public void testManagementOperations() throws Exception {89 testNonManagementOperation();90 testManagementOperationErrors();91 testGetToken(null, new Text("foo"));92 testGetToken("bar", new Text("foo"));93 testCancelToken();94 testRenewToken();95 }96 private void testNonManagementOperation() throws Exception {97 HttpServletRequest request = Mockito.mock(HttpServletRequest.class);98 Mockito.when(request.getParameter(99 DelegationTokenAuthenticator.OP_PARAM)).thenReturn(null);100 Assert.assertTrue(handler.managementOperation(null, request, null));101 Mockito.when(request.getParameter(102 DelegationTokenAuthenticator.OP_PARAM)).thenReturn("CREATE");103 Assert.assertTrue(handler.managementOperation(null, request, null));104 }105 private void testManagementOperationErrors() throws Exception {106 HttpServletRequest request = Mockito.mock(HttpServletRequest.class);107 HttpServletResponse response = Mockito.mock(HttpServletResponse.class);108 Mockito.when(request.getQueryString()).thenReturn(109 DelegationTokenAuthenticator.OP_PARAM + "=" +110 DelegationTokenAuthenticator.DelegationTokenOperation.111 GETDELEGATIONTOKEN.toString()112 );113 Mockito.when(request.getMethod()).thenReturn("FOO");114 Assert.assertFalse(handler.managementOperation(null, request, response));115 Mockito.verify(response).sendError(116 Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),117 Mockito.startsWith("Wrong HTTP method"));118 Mockito.reset(response);119 Mockito.when(request.getMethod()).thenReturn(120 DelegationTokenAuthenticator.DelegationTokenOperation.121 GETDELEGATIONTOKEN.getHttpMethod()122 );123 Assert.assertFalse(handler.managementOperation(null, request, response));124 Mockito.verify(response).setStatus(125 Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED));126 Mockito.verify(response).setHeader(127 Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),128 Mockito.eq("mock"));129 }130 private void testGetToken(String renewer, Text expectedTokenKind)131 throws Exception {132 DelegationTokenAuthenticator.DelegationTokenOperation op =133 DelegationTokenAuthenticator.DelegationTokenOperation.134 GETDELEGATIONTOKEN;135 HttpServletRequest request = Mockito.mock(HttpServletRequest.class);136 HttpServletResponse response = Mockito.mock(HttpServletResponse.class);137 Mockito.when(request.getQueryString()).138 thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString());139 Mockito.when(request.getMethod()).thenReturn(op.getHttpMethod());140 AuthenticationToken token = Mockito.mock(AuthenticationToken.class);141 Mockito.when(token.getUserName()).thenReturn("user");142 Mockito.when(response.getWriter()).thenReturn(new PrintWriter(143 new StringWriter()));144 Assert.assertFalse(handler.managementOperation(token, request, response));145 Mockito.when(request.getQueryString()).146 thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString() +147 "&" + DelegationTokenAuthenticator.RENEWER_PARAM + "=" + renewer);148 Mockito.reset(response);149 Mockito.reset(token);150 Mockito.when(token.getUserName()).thenReturn("user");151 StringWriter writer = new StringWriter();152 PrintWriter pwriter = new PrintWriter(writer);153 Mockito.when(response.getWriter()).thenReturn(pwriter);154 Assert.assertFalse(handler.managementOperation(token, request, response));155 if (renewer == null) {156 Mockito.verify(token).getUserName();157 } else {158 Mockito.verify(token).getUserName();159 }160 Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);161 Mockito.verify(response).setContentType(MediaType.APPLICATION_JSON);162 pwriter.close();163 String responseOutput = writer.toString();164 String tokenLabel = DelegationTokenAuthenticator.165 DELEGATION_TOKEN_JSON;166 Assert.assertTrue(responseOutput.contains(tokenLabel));167 Assert.assertTrue(responseOutput.contains(168 DelegationTokenAuthenticator.DELEGATION_TOKEN_URL_STRING_JSON));169 ObjectMapper jsonMapper = new ObjectMapper();170 Map json = jsonMapper.readValue(responseOutput, Map.class);171 json = (Map) json.get(tokenLabel);172 String tokenStr;173 tokenStr = (String) json.get(DelegationTokenAuthenticator.174 DELEGATION_TOKEN_URL_STRING_JSON);175 Token<DelegationTokenIdentifier> dt = new Token<DelegationTokenIdentifier>();176 dt.decodeFromUrlString(tokenStr);177 handler.getTokenManager().verifyToken(dt);178 Assert.assertEquals(expectedTokenKind, dt.getKind());179 }180 @SuppressWarnings("unchecked")181 private void testCancelToken() throws Exception {182 DelegationTokenAuthenticator.DelegationTokenOperation op =183 DelegationTokenAuthenticator.DelegationTokenOperation.184 CANCELDELEGATIONTOKEN;185 HttpServletRequest request = Mockito.mock(HttpServletRequest.class);186 HttpServletResponse response = Mockito.mock(HttpServletResponse.class);187 Mockito.when(request.getQueryString()).thenReturn(188 DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString());189 Mockito.when(request.getMethod()).190 thenReturn(op.getHttpMethod());191 Assert.assertFalse(handler.managementOperation(null, request, response));192 Mockito.verify(response).sendError(193 Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),194 Mockito.contains("requires the parameter [token]"));195 Mockito.reset(response);196 Token<DelegationTokenIdentifier> token =197 (Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(198 UserGroupInformation.getCurrentUser(), "foo");199 Mockito.when(request.getQueryString()).thenReturn(200 DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString() + "&" +201 DelegationTokenAuthenticator.TOKEN_PARAM + "=" +202 token.encodeToUrlString()203 );204 Assert.assertFalse(handler.managementOperation(null, request, response));205 Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);206 try {207 handler.getTokenManager().verifyToken(token);208 Assert.fail();209 } catch (SecretManager.InvalidToken ex) {210 //NOP211 } catch (Throwable ex) {212 Assert.fail();213 }214 }215 @SuppressWarnings("unchecked")216 private void testRenewToken() throws Exception {217 DelegationTokenAuthenticator.DelegationTokenOperation op =218 DelegationTokenAuthenticator.DelegationTokenOperation.219 RENEWDELEGATIONTOKEN;220 HttpServletRequest request = Mockito.mock(HttpServletRequest.class);221 HttpServletResponse response = Mockito.mock(HttpServletResponse.class);222 Mockito.when(request.getQueryString()).223 thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString());224 Mockito.when(request.getMethod()).225 thenReturn(op.getHttpMethod());226 Assert.assertFalse(handler.managementOperation(null, request, response));227 Mockito.verify(response).setStatus(228 Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED));229 Mockito.verify(response).setHeader(Mockito.eq(230 KerberosAuthenticator.WWW_AUTHENTICATE),231 Mockito.eq("mock")232 );233 Mockito.reset(response);234 AuthenticationToken token = Mockito.mock(AuthenticationToken.class);235 Mockito.when(token.getUserName()).thenReturn("user");236 Assert.assertFalse(handler.managementOperation(token, request, response));237 Mockito.verify(response).sendError(238 Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),239 Mockito.contains("requires the parameter [token]"));240 Mockito.reset(response);241 StringWriter writer = new StringWriter();242 PrintWriter pwriter = new PrintWriter(writer);243 Mockito.when(response.getWriter()).thenReturn(pwriter);244 Token<DelegationTokenIdentifier> dToken =245 (Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(246 UserGroupInformation.getCurrentUser(), "user");247 Mockito.when(request.getQueryString()).248 thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString() +249 "&" + DelegationTokenAuthenticator.TOKEN_PARAM + "=" +250 dToken.encodeToUrlString());251 Assert.assertFalse(handler.managementOperation(token, request, response));252 Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);253 pwriter.close();254 Assert.assertTrue(writer.toString().contains("long"));255 handler.getTokenManager().verifyToken(dToken);256 }257 @Test258 public void testAuthenticate() throws Exception {259 testValidDelegationTokenQueryString();260 testValidDelegationTokenHeader();261 testInvalidDelegationTokenQueryString();262 testInvalidDelegationTokenHeader();263 }264 @SuppressWarnings("unchecked")265 private void testValidDelegationTokenQueryString() throws Exception {266 HttpServletRequest request = Mockito.mock(HttpServletRequest.class);267 HttpServletResponse response = Mockito.mock(HttpServletResponse.class);268 Token<DelegationTokenIdentifier> dToken =269 (Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(270 UserGroupInformation.getCurrentUser(), "user");271 Mockito.when(request.getQueryString()).thenReturn(272 DelegationTokenAuthenticator.DELEGATION_PARAM + "=" +273 dToken.encodeToUrlString());274 AuthenticationToken token = handler.authenticate(request, response);275 Assert.assertEquals(UserGroupInformation.getCurrentUser().276 getShortUserName(), token.getUserName());277 Assert.assertEquals(0, token.getExpires());278 Assert.assertEquals(handler.getType(),279 token.getType());280 Assert.assertTrue(token.isExpired());281 }282 @SuppressWarnings("unchecked")283 private void testValidDelegationTokenHeader() throws Exception {284 HttpServletRequest request = Mockito.mock(HttpServletRequest.class);285 HttpServletResponse response = Mockito.mock(HttpServletResponse.class);286 Token<DelegationTokenIdentifier> dToken =287 (Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(288 UserGroupInformation.getCurrentUser(), "user");289 Mockito.when(request.getHeader(Mockito.eq(290 DelegationTokenAuthenticator.DELEGATION_TOKEN_HEADER))).thenReturn(291 dToken.encodeToUrlString());292 AuthenticationToken token = handler.authenticate(request, response);293 Assert.assertEquals(UserGroupInformation.getCurrentUser().294 getShortUserName(), token.getUserName());295 Assert.assertEquals(0, token.getExpires());296 Assert.assertEquals(handler.getType(),297 token.getType());298 Assert.assertTrue(token.isExpired());299 }300 private void testInvalidDelegationTokenQueryString() throws Exception {301 HttpServletRequest request = Mockito.mock(HttpServletRequest.class);302 HttpServletResponse response = Mockito.mock(HttpServletResponse.class);303 Mockito.when(request.getQueryString()).thenReturn(304 DelegationTokenAuthenticator.DELEGATION_PARAM + "=invalid");305 StringWriter writer = new StringWriter();306 Mockito.when(response.getWriter()).thenReturn(new PrintWriter(writer));307 Assert.assertNull(handler.authenticate(request, response));308 Mockito.verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN);309 Assert.assertTrue(writer.toString().contains("AuthenticationException"));310 }311 private void testInvalidDelegationTokenHeader() throws Exception {312 HttpServletRequest request = Mockito.mock(HttpServletRequest.class);313 HttpServletResponse response = Mockito.mock(HttpServletResponse.class);314 Mockito.when(request.getHeader(Mockito.eq(315 DelegationTokenAuthenticator.DELEGATION_TOKEN_HEADER))).thenReturn(316 "invalid");317 StringWriter writer = new StringWriter();318 Mockito.when(response.getWriter()).thenReturn(new PrintWriter(writer));319 Assert.assertNull(handler.authenticate(request, response));320 Assert.assertTrue(writer.toString().contains("AuthenticationException"));321 }322}...
Source:UserServiceTest.java
...22import org.junit.Before;23import org.junit.Test;24import org.junit.runner.RunWith;25import org.mockito.Mockito;26import org.shanoir.ng.accountrequest.model.AccountRequestInfo;27import org.shanoir.ng.accountrequest.repository.AccountRequestInfoRepository;28import org.shanoir.ng.email.EmailService;29import org.shanoir.ng.extensionrequest.model.ExtensionRequestInfo;30import org.shanoir.ng.role.repository.RoleRepository;31import org.shanoir.ng.shared.core.model.IdName;32import org.shanoir.ng.shared.exception.AccountNotOnDemandException;33import org.shanoir.ng.shared.exception.EntityNotFoundException;34import org.shanoir.ng.shared.exception.ForbiddenException;35import org.shanoir.ng.shared.exception.SecurityException;36import org.shanoir.ng.shared.exception.ShanoirUsersException;37import org.shanoir.ng.user.model.User;38import org.shanoir.ng.user.repository.UserRepository;39import org.shanoir.ng.user.service.UserService;40import org.shanoir.ng.user.utils.KeycloakClient;41import org.shanoir.ng.utils.ModelsUtil;42import org.shanoir.ng.utils.usermock.WithMockKeycloakUser;43import org.springframework.amqp.rabbit.core.RabbitTemplate;44import org.springframework.beans.factory.annotation.Autowired;45import org.springframework.boot.test.context.SpringBootTest;46import org.springframework.boot.test.mock.mockito.MockBean;47import org.springframework.context.ApplicationEventPublisher;48import org.springframework.security.access.AccessDeniedException;49import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;50import org.springframework.security.test.context.support.WithAnonymousUser;51import org.springframework.security.test.context.support.WithMockUser;52import org.springframework.test.context.ActiveProfiles;53import org.springframework.test.context.junit4.SpringRunner;54/**55 * User detail service test.56 * 57 * @author msimon58 * 59 */60@RunWith(SpringRunner.class)61@SpringBootTest62@ActiveProfiles("test")63@EnableGlobalMethodSecurity(prePostEnabled = true)64public class UserServiceTest {65 private static final long USER_ID = 1L;66 private static final String UPDATED_USER_FIRSTNAME = "test";67 private static final String USER_USERNAME = "name";68 @MockBean69 private AccountRequestInfoRepository accountRequestInfoRepository;70 @MockBean71 private EmailService emailService;72 @MockBean73 private KeycloakClient keycloakClient;74 @MockBean75 private RabbitTemplate rabbitTemplate;76 @MockBean77 private RoleRepository roleRepository;78 @MockBean79 private UserRepository userRepository;80 81 @MockBean82 private ApplicationEventPublisher publisher;83 @Autowired84 private UserService userService;85 @Before86 public void setup() throws SecurityException {87 given(userRepository.findAll()).willReturn(Arrays.asList(ModelsUtil.createUser()));88 given(userRepository.findByUsername(Mockito.anyString())).willReturn(Optional.of(ModelsUtil.createUser()));89 given(userRepository.findByIdIn(Mockito.anyListOf(Long.class)))90 .willReturn(Arrays.asList(createUser()));91 given(userRepository.findOne(USER_ID)).willReturn(ModelsUtil.createUser(USER_ID));92 given(userRepository93 .findByExpirationDateLessThanAndFirstExpirationNotificationSentFalse(Mockito.any(LocalDate.class)))94 .willReturn(Arrays.asList(ModelsUtil.createUser()));95 given(userRepository96 .findByExpirationDateLessThanAndSecondExpirationNotificationSentFalse(Mockito.any(LocalDate.class)))97 .willReturn(Arrays.asList(ModelsUtil.createUser()));98 given(userRepository.save(Mockito.any(User.class))).willReturn(ModelsUtil.createUser());99 given(roleRepository.findByName(Mockito.anyString())).willReturn(ModelsUtil.createUserRole());100 given(keycloakClient.createUserWithPassword(Mockito.any(User.class), Mockito.anyString())).willReturn(RandomStringUtils.randomAlphanumeric(10));101 }102 @Test103 @WithMockUser(authorities = { "ROLE_ADMIN" })104 public void confirmAccountRequestTest() throws AccountNotOnDemandException, EntityNotFoundException {105 final User user = ModelsUtil.createUser();106 user.setAccountRequestDemand(true);107 given(userRepository.findOne(USER_ID)).willReturn(user);108 final User updatedUser = userService.confirmAccountRequest(createUser());109 Assert.assertNotNull(updatedUser);110 Assert.assertTrue(UPDATED_USER_FIRSTNAME.equals(updatedUser.getFirstName()));111 Mockito.verify(userRepository, Mockito.times(1)).findOne(Mockito.anyLong());112 user.setAccountRequestDemand(false);113 Mockito.verify(userRepository, Mockito.times(1)).save(user);114 }115 @Test(expected = EntityNotFoundException.class)116 @WithMockUser(authorities = { "ROLE_ADMIN" })117 public void confirmAccountRequestBadUserIdTest() throws EntityNotFoundException, AccountNotOnDemandException {118 given(userRepository.findOne(USER_ID)).willReturn(null);119 userService.confirmAccountRequest(new User());120 Mockito.verify(userRepository, Mockito.times(1)).findOne(Mockito.anyLong());121 Mockito.verify(userRepository, Mockito.times(0)).save(Mockito.any(User.class));122 }123 @Test(expected = ShanoirUsersException.class)124 @WithMockUser(authorities = { "ROLE_ADMIN" })125 public void confirmAccountRequestNoDemandTest() throws AccountNotOnDemandException, EntityNotFoundException {126 User user = ModelsUtil.createUser(USER_ID);127 given(userRepository.findOne(USER_ID)).willReturn(user);128 129 userService.confirmAccountRequest(user);130 Mockito.verify(userRepository, Mockito.times(1)).findOne(Mockito.anyLong());131 Mockito.verify(userRepository, Mockito.times(0)).save(Mockito.any(User.class));132 }133 @Test134 @WithMockUser(authorities = { "ROLE_ADMIN" })135 public void denyAccountRequestTest() throws AccountNotOnDemandException, EntityNotFoundException {136 final User user = ModelsUtil.createUser();137 user.setAccountRequestDemand(true);138 given(userRepository.findOne(USER_ID)).willReturn(user);139 userService.denyAccountRequest(USER_ID);140 Mockito.verify(userRepository, Mockito.times(1)).findOne(Mockito.anyLong());141 Mockito.verify(userRepository, Mockito.times(1)).delete(USER_ID);142 }143 @Test(expected = EntityNotFoundException.class)144 @WithMockUser(authorities = { "ROLE_ADMIN" })145 public void denyAccountRequestBadUserIdTest() throws AccountNotOnDemandException, EntityNotFoundException {146 given(userRepository.findOne(USER_ID)).willReturn(null);147 userService.denyAccountRequest(USER_ID);148 Mockito.verify(userRepository, Mockito.times(1)).findOne(Mockito.anyLong());149 Mockito.verify(userRepository, Mockito.times(0)).delete(USER_ID);150 }151 @Test(expected = AccountNotOnDemandException.class)152 @WithMockUser(authorities = { "ROLE_ADMIN" })153 public void denyAccountRequestNoDemandTest() throws EntityNotFoundException, AccountNotOnDemandException {154 given(userRepository.findOne(USER_ID)).willReturn(ModelsUtil.createUser());155 userService.denyAccountRequest(USER_ID);156 Mockito.verify(userRepository, Mockito.times(1)).findOne(Mockito.anyLong());157 Mockito.verify(userRepository, Mockito.times(0)).delete(USER_ID);158 }159 @Test160 @WithMockKeycloakUser(id = 2L, authorities = { "ROLE_ADMIN" })161 public void deleteByIdTest() throws EntityNotFoundException, ForbiddenException {162 userService.deleteById(USER_ID);163 Mockito.verify(userRepository, Mockito.times(1)).delete(Mockito.anyLong());164 }165 @Test(expected = AccessDeniedException.class)166 @WithMockKeycloakUser(id = USER_ID, authorities = { "ROLE_ADMIN" })167 public void deleteByIdByUserWithSameIdTest() throws EntityNotFoundException, ForbiddenException {168 userService.deleteById(USER_ID);169 Mockito.verify(userRepository, Mockito.times(1)).delete(Mockito.anyLong());170 }171 @Test172 @WithMockUser(authorities = { "ROLE_ADMIN" })173 public void findAllTest() {174 final List<User> users = userService.findAll();175 Assert.assertNotNull(users);176 Assert.assertTrue(users.size() == 1);177 Mockito.verify(userRepository, Mockito.times(1)).findAll();178 }179 @Test180 @WithMockKeycloakUser(id = USER_ID, authorities = { "ROLE_USER" })181 public void findByIdTest() {182 final User user = userService.findById(USER_ID);183 Assert.assertNotNull(user);184 Assert.assertTrue(ModelsUtil.USER_FIRSTNAME.equals(user.getFirstName()));185 Mockito.verify(userRepository, Mockito.times(1)).findOne(Mockito.anyLong());186 }187 @Test188 @WithMockUser(authorities = { "ROLE_USER" })189 public void findByIdsTest() {190 final List<IdName> users = userService.findByIds(Arrays.asList(USER_ID));191 Assert.assertNotNull(users);192 Assert.assertTrue(USER_USERNAME.equals(users.get(0).getName()));193 Mockito.verify(userRepository, Mockito.times(1)).findByIdIn(Arrays.asList(USER_ID));194 }195 @Test196 @WithMockUser(authorities = { "ROLE_ADMIN" })197 public void getUsersToReceiveFirstExpirationNotificationTest() {198 final List<User> users = userService.getUsersToReceiveFirstExpirationNotification();199 Assert.assertNotNull(users);200 Assert.assertTrue(users.size() == 1);201 Assert.assertTrue(ModelsUtil.USER_FIRSTNAME.equals(users.get(0).getFirstName()));202 Mockito.verify(userRepository, Mockito.times(1))203 .findByExpirationDateLessThanAndFirstExpirationNotificationSentFalse(Mockito.any(LocalDate.class));204 }205 @Test206 @WithMockUser(authorities = { "ROLE_ADMIN" })207 public void getUsersToReceiveSecondExpirationNotificationTest() {208 final List<User> users = userService.getUsersToReceiveSecondExpirationNotification();209 Assert.assertNotNull(users);210 Assert.assertTrue(users.size() == 1);211 Assert.assertTrue(ModelsUtil.USER_FIRSTNAME.equals(users.get(0).getFirstName()));212 Mockito.verify(userRepository, Mockito.times(1))213 .findByExpirationDateLessThanAndSecondExpirationNotificationSentFalse(Mockito.any(LocalDate.class));214 }215 @Test216 public void requestExtensionTest() throws EntityNotFoundException {217 ExtensionRequestInfo requestInfo = new ExtensionRequestInfo();218 requestInfo.setExtensionDate(LocalDate.now());219 requestInfo.setExtensionMotivation("motivation");220 userService.requestExtension(USER_ID, requestInfo);221 Mockito.verify(userRepository, Mockito.times(1)).save(Mockito.any(User.class));222 Mockito.verify(emailService, Mockito.times(1)).notifyAdminAccountExtensionRequest(Mockito.any(User.class));223 }224 @Test225 @WithMockUser(authorities = { "ROLE_ADMIN" })226 public void saveTest() throws SecurityException {227 User newUser = createUser();228 newUser.setId(null);229 userService.create(newUser);230 Mockito.verify(userRepository, Mockito.times(2)).save(Mockito.any(User.class));231 Mockito.verify(accountRequestInfoRepository, Mockito.times(0)).save(Mockito.any(AccountRequestInfo.class));232 }233 @Test234 @WithAnonymousUser...
Source:NoticesExecutor_IT.java
...41 OleCirculationDesk oleCirculationDesk = Mockito.mock(OleCirculationDesk.class);42 oleDeliverRequestBo.setOlePickUpLocation(oleCirculationDesk);43 List<OleDeliverRequestBo> oleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();44 oleDeliverRequestBoList.add(oleDeliverRequestBo);45 Map requestMap = new HashMap();46 requestMap.put(OLEConstants.NOTICE_CONTENT_CONFIG_NAME, "Request Expiration");47 requestMap.put(OLEConstants.DELIVER_NOTICES, new ArrayList<OLEDeliverNotice>());48 RequestExpirationNoticesExecutor requestExpirationNoticesExecutor = new RequestExpirationNoticesExecutor(requestMap);49 ParameterValueResolver parameterValueResolver = Mockito.mock(ParameterValueResolver.class);50 Mockito.when(parameterValueResolver.getParameter(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(),Mockito.eq(" EXP_REQ_TITLE"))).thenReturn("Request Expiration Notice");51 Mockito.when(parameterValueResolver.getParameter(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(), Mockito.eq("EXP_REQ_BODY"))).thenReturn("Your Request Place on the item 1 is expired");52 // requestExpirationNoticesExecutor.setParameterResolverInstance(parameterValueResolver);53 RequestExpirationEmailContentFormatter noticeRequestExpirationEmailContentFormatter = Mockito.spy(new RequestExpirationEmailContentFormatter());54 OlePatronHelperService olePatronHelperService = Mockito.mock(OlePatronHelperService.class);55 try{56 Mockito.when(olePatronHelperService.getPatronHomeEmailId(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("Mahesh@htcindia.com");57 Mockito.when(olePatronHelperService.getPatronHomePhoneNumber(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("1234-1234-1234");58 Mockito.when(olePatronHelperService.getPatronPreferredAddress(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("chennai");59 }catch(Exception e){60 }61 noticeRequestExpirationEmailContentFormatter.setOlePatronHelperService(olePatronHelperService);62 requestExpirationNoticesExecutor.generateMailContent();63 }64 @Test65 public void testGenerateRequestHoldExpirationNoticesMailContent(){66 OleDeliverRequestBo oleDeliverRequestBo = Mockito.mock(OleDeliverRequestBo.class);67 OlePatronDocument olePatronDocument = Mockito.mock(OlePatronDocument.class);68 oleDeliverRequestBo.setOlePatron(olePatronDocument);69 OleCirculationDesk oleCirculationDesk = Mockito.mock(OleCirculationDesk.class);70 oleDeliverRequestBo.setOlePickUpLocation(oleCirculationDesk);71 List<OleDeliverRequestBo> oleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();72 oleDeliverRequestBoList.add(oleDeliverRequestBo);73 Map requestMap = new HashMap();74 requestMap.put(OLEConstants.NOTICE_CONTENT_CONFIG_NAME, "On Hold Expiration Notice");75 requestMap.put(OLEConstants.DELIVER_NOTICES, new ArrayList<OLEDeliverNotice>());76 HoldExpirationNoticesExecutor holdExpirationNoticesExecutor = new HoldExpirationNoticesExecutor(requestMap);77 ParameterValueResolver parameterValueResolver = Mockito.mock(ParameterValueResolver.class);78 Mockito.when(parameterValueResolver.getParameter(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(),Mockito.eq("EXPIRED_TITLE"))).thenReturn("Hold Courtesy Notice");79 Mockito.when(parameterValueResolver.getParameter(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(), Mockito.eq("EXP_HOLD_NOTICE_CONTENT"))).thenReturn("The item is kept hold in the circulation desk for you to pick up .since you haven't picked up the book the item is moved to shelf.Place a new Request for that item");80 //holdExpirationNoticesExecutor.setParameterResolverInstance(parameterValueResolver);81 RequestExpirationEmailContentFormatter noticeRequestExpirationEmailContentFormatter = Mockito.spy(new RequestExpirationEmailContentFormatter());82 OlePatronHelperService olePatronHelperService = Mockito.mock(OlePatronHelperService.class);83 try{84 Mockito.when(olePatronHelperService.getPatronHomeEmailId(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("Mahesh@htcindia.com");85 Mockito.when(olePatronHelperService.getPatronHomePhoneNumber(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("1234-1234-1234");86 Mockito.when(olePatronHelperService.getPatronPreferredAddress(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("chennai");87 }catch(Exception e){88 }89 noticeRequestExpirationEmailContentFormatter.setOlePatronHelperService(olePatronHelperService);90 holdExpirationNoticesExecutor.generateMailContent();91 }92 @Test93 public void testGenerateHoldNoticesMailContent(){94 OleDeliverRequestBo oleDeliverRequestBo = Mockito.mock(OleDeliverRequestBo.class);95 OlePatronDocument olePatronDocument = Mockito.mock(OlePatronDocument.class);96 oleDeliverRequestBo.setOlePatron(olePatronDocument);97 OleCirculationDesk oleCirculationDesk = Mockito.mock(OleCirculationDesk.class);98 oleDeliverRequestBo.setOlePickUpLocation(oleCirculationDesk);99 List<OleDeliverRequestBo> oleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();100 oleDeliverRequestBoList.add(oleDeliverRequestBo);101 Map requestMap = new HashMap();102 requestMap.put(OLEConstants.NOTICE_CONTENT_CONFIG_NAME, "On Hold Expiration Notice");103 requestMap.put(OLEConstants.DELIVER_NOTICES, new ArrayList<OLEDeliverNotice>());104 HoldExpirationNoticesExecutor holdExpirationNoticesExecutor = new HoldExpirationNoticesExecutor(requestMap);105 ParameterValueResolver parameterValueResolver = Mockito.mock(ParameterValueResolver.class);106 Mockito.when(parameterValueResolver.getParameter(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(),Mockito.eq("ONHOLD_TITLE"))).thenReturn("On Hold Notice");107 Mockito.when(parameterValueResolver.getParameter(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(), Mockito.eq("ONHOLD_BODY"))).thenReturn("The request you have on the item is available to pick up and the item will be on hold for you till 22nd of june ");108 //holdExpirationNoticesExecutor.setParameterResolverInstance(parameterValueResolver);109 RecallRequestEmailContentFormatter noticeRequestExpirationEmailContentFormatter = Mockito.spy(new RecallRequestEmailContentFormatter());110 OlePatronHelperService olePatronHelperService = Mockito.mock(OlePatronHelperService.class);111 try{112 Mockito.when(olePatronHelperService.getPatronHomeEmailId(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("Mahesh@htcindia.com");113 Mockito.when(olePatronHelperService.getPatronHomePhoneNumber(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("1234-1234-1234");114 Mockito.when(olePatronHelperService.getPatronPreferredAddress(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("chennai");115 }catch(Exception e){116 }117 noticeRequestExpirationEmailContentFormatter.setOlePatronHelperService(olePatronHelperService);118 holdExpirationNoticesExecutor.generateMailContent();119 }120 @Test121 public void testGenerateRecallNoticesMailContent(){122 OleDeliverRequestBo oleDeliverRequestBo = Mockito.mock(OleDeliverRequestBo.class);123 OlePatronDocument olePatronDocument = Mockito.mock(OlePatronDocument.class);124 oleDeliverRequestBo.setOlePatron(olePatronDocument);125 OleCirculationDesk oleCirculationDesk = Mockito.mock(OleCirculationDesk.class);126 oleDeliverRequestBo.setOlePickUpLocation(oleCirculationDesk);127 Mockito.when(oleDeliverRequestBo.getOriginalDueDate()).thenReturn(new Date(7, 7, 2015));128 Mockito.when(oleDeliverRequestBo.getRecallDueDate()).thenReturn(new Timestamp(2015,7,1,0,0,0,0));129 List<OleDeliverRequestBo> oleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();130 oleDeliverRequestBoList.add(oleDeliverRequestBo);131 Map requestMap = new HashMap();132 requestMap.put(OLEConstants.NOTICE_CONTENT_CONFIG_NAME, "Recall Notice");133 requestMap.put(OLEConstants.DELIVER_NOTICES, new ArrayList<OLEDeliverNotice>());134 RecallNoticesExecutor holdExpirationNoticesExecutor = new RecallNoticesExecutor(requestMap);135 ParameterValueResolver parameterValueResolver = Mockito.mock(ParameterValueResolver.class);136 Mockito.when(parameterValueResolver.getParameter(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(),Mockito.eq("RECALL_TITLE"))).thenReturn("Recall Notice");137 Mockito.when(parameterValueResolver.getParameter(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(), Mockito.eq("RECALL_BODY"))).thenReturn("Item is needed by another patron .so kindly return the item before the date specified below");138 //holdExpirationNoticesExecutor.setParameterResolverInstance(parameterValueResolver);139 RecallRequestEmailContentFormatter noticeRequestExpirationEmailContentFormatter = Mockito.spy(new RecallRequestEmailContentFormatter());140 OlePatronHelperService olePatronHelperService = Mockito.mock(OlePatronHelperServiceImpl.class);141 noticeRequestExpirationEmailContentFormatter.setOlePatronHelperService(olePatronHelperService);142 try{143 Mockito.when(olePatronHelperService.getPatronHomeEmailId(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("Mahesh@htcindia.com");144 Mockito.when(olePatronHelperService.getPatronHomePhoneNumber(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("1234-1234-1234");145 Mockito.when(olePatronHelperService.getPatronPreferredAddress(Mockito.any(EntityTypeContactInfoBo.class))).thenReturn("chennai");146 }catch(Exception e){147 }148 holdExpirationNoticesExecutor.setRequestEmailContentFormatter(noticeRequestExpirationEmailContentFormatter);...
Source:LoggingFilterTest.java
...21import static org.mockito.Mockito.when;22@RunWith(MockitoJUnitRunner.class)23public class LoggingFilterTest {24 @Mock25 private RequestLogRepository requestLogRepository;26 @Mock27 private Logger logger;28 @InjectMocks29 @Autowired30 private LoggingFilter loggingFilter;31 @Mock32 private ApiSettings settings;33 @Test34 public void testDoFilterPut() throws Exception {35 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);36 HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);37 FilterChain filterChain = Mockito.mock(FilterChain.class);38 when(httpServletRequest.getInputStream()).thenReturn(Mockito.mock(ServletInputStream.class));39 when(httpServletRequest.getRequestURI()).thenReturn("Success");40 when(httpServletRequest.getMethod()).thenReturn(HttpMethod.PUT.toString());41 when(settings.isLogRequest()).thenReturn(true);42 when(requestLogRepository.save(any(RequestLog.class))).thenReturn(new RequestLog());43 when(httpServletRequest.getContentType()).thenReturn("application/json;charset=UTF-8");44 when(httpServletResponse.getContentType()).thenReturn("application/json;charset=UTF-8");45 loggingFilter.doFilter(httpServletRequest, httpServletResponse,46 filterChain);47 verify(requestLogRepository, times(1)).save(any(RequestLog.class));48 }49 @Test50 public void testDoFilterGet() throws Exception {51 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);52 HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);53 FilterChain filterChain = Mockito.mock(FilterChain.class);54 when(httpServletRequest.getInputStream()).thenReturn(Mockito.mock(ServletInputStream.class));55 when(httpServletRequest.getRequestURI()).thenReturn("Success");56 when(httpServletRequest.getMethod()).thenReturn(HttpMethod.GET.toString());57 when(requestLogRepository.save(any(RequestLog.class))).thenReturn(new RequestLog());58 when(httpServletRequest.getContentType()).thenReturn("application/json;charset=UTF-8");59 when(httpServletResponse.getContentType()).thenReturn("application/json;charset=UTF-8");60 when(settings.isLogRequest()).thenReturn(true);61 loggingFilter.doFilter(httpServletRequest, httpServletResponse,62 filterChain);63 verify(requestLogRepository, times(0)).save(any(RequestLog.class));64 }65 @Test66 public void testDoFilterPost() throws Exception {67 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);68 HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);69 FilterChain filterChain = Mockito.mock(FilterChain.class);70 when(httpServletRequest.getInputStream()).thenReturn(Mockito.mock(ServletInputStream.class));71 when(httpServletRequest.getRequestURI()).thenReturn("Success");72 when(httpServletRequest.getMethod()).thenReturn(HttpMethod.POST.toString());73 when(requestLogRepository.save(any(RequestLog.class))).thenReturn(new RequestLog());74 when(httpServletRequest.getContentType()).thenReturn("application/json;charset=UTF-8");75 when(httpServletResponse.getContentType()).thenReturn("application/json;charset=UTF-8");76 when(settings.isLogRequest()).thenReturn(true);77 loggingFilter.doFilter(httpServletRequest, httpServletResponse,78 filterChain);79 verify(requestLogRepository, times(1)).save(any(RequestLog.class));80 }81 @Test82 public void testDoFilterDelete() throws Exception {83 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);84 HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);85 FilterChain filterChain = Mockito.mock(FilterChain.class);86 when(httpServletRequest.getInputStream()).thenReturn(Mockito.mock(ServletInputStream.class));87 when(httpServletRequest.getRequestURI()).thenReturn("Success");88 when(httpServletRequest.getMethod()).thenReturn(HttpMethod.DELETE.toString());89 when(requestLogRepository.save(any(RequestLog.class))).thenReturn(new RequestLog());90 when(httpServletRequest.getContentType()).thenReturn("application/json;charset=UTF-8");91 when(httpServletResponse.getContentType()).thenReturn("application/json;charset=UTF-8");92 when(settings.isLogRequest()).thenReturn(true);93 loggingFilter.doFilter(httpServletRequest, httpServletResponse,94 filterChain);95 verify(requestLogRepository, times(1)).save(any(RequestLog.class));96 }97 @Test98 public void testDoFilterPutSettingOff() throws Exception {99 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);100 HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);101 FilterChain filterChain = Mockito.mock(FilterChain.class);102 when(httpServletRequest.getInputStream()).thenReturn(Mockito.mock(ServletInputStream.class));103 when(httpServletRequest.getRequestURI()).thenReturn("Success");104 when(httpServletRequest.getMethod()).thenReturn(HttpMethod.PUT.toString());105 when(settings.isLogRequest()).thenReturn(false);106 when(requestLogRepository.save(any(RequestLog.class))).thenReturn(new RequestLog());107 when(httpServletRequest.getContentType()).thenReturn("application/json;charset=UTF-8");108 when(httpServletResponse.getContentType()).thenReturn("application/json;charset=UTF-8");109 loggingFilter.doFilter(httpServletRequest, httpServletResponse,110 filterChain);111 verify(requestLogRepository, times(0)).save(any(RequestLog.class));112 }113 @Test114 public void testDoFilterGetSettingsOff() throws Exception {115 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);116 HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);117 FilterChain filterChain = Mockito.mock(FilterChain.class);118 when(httpServletRequest.getInputStream()).thenReturn(Mockito.mock(ServletInputStream.class));119 when(httpServletRequest.getRequestURI()).thenReturn("Success");120 when(httpServletRequest.getMethod()).thenReturn(HttpMethod.GET.toString());121 when(requestLogRepository.save(any(RequestLog.class))).thenReturn(new RequestLog());122 when(httpServletRequest.getContentType()).thenReturn("application/json;charset=UTF-8");123 when(httpServletResponse.getContentType()).thenReturn("application/json;charset=UTF-8");124 when(settings.isLogRequest()).thenReturn(false);125 loggingFilter.doFilter(httpServletRequest, httpServletResponse,126 filterChain);127 verify(requestLogRepository, times(0)).save(any(RequestLog.class));128 }129 @Test130 public void testDoFilterPostSettingsOff() throws Exception {131 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);132 HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);133 FilterChain filterChain = Mockito.mock(FilterChain.class);134 when(httpServletRequest.getInputStream()).thenReturn(Mockito.mock(ServletInputStream.class));135 when(httpServletRequest.getRequestURI()).thenReturn("Success");136 when(httpServletRequest.getMethod()).thenReturn(HttpMethod.POST.toString());137 when(requestLogRepository.save(any(RequestLog.class))).thenReturn(new RequestLog());138 when(httpServletRequest.getContentType()).thenReturn("application/json;charset=UTF-8");139 when(httpServletResponse.getContentType()).thenReturn("application/json;charset=UTF-8");140 when(settings.isLogRequest()).thenReturn(false);141 loggingFilter.doFilter(httpServletRequest, httpServletResponse,142 filterChain);143 verify(requestLogRepository, times(0)).save(any(RequestLog.class));144 }145 @Test146 public void testDoFilterDeleteSettingsOff() throws Exception {147 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);148 HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);149 FilterChain filterChain = Mockito.mock(FilterChain.class);150 when(httpServletRequest.getInputStream()).thenReturn(Mockito.mock(ServletInputStream.class));151 when(httpServletRequest.getRequestURI()).thenReturn("Success");152 when(httpServletRequest.getMethod()).thenReturn(HttpMethod.DELETE.toString());153 when(requestLogRepository.save(any(RequestLog.class))).thenReturn(new RequestLog());154 when(httpServletRequest.getContentType()).thenReturn("application/json;charset=UTF-8");155 when(httpServletResponse.getContentType()).thenReturn("application/json;charset=UTF-8");156 when(settings.isLogRequest()).thenReturn(false);157 loggingFilter.doFilter(httpServletRequest, httpServletResponse,158 filterChain);159 verify(requestLogRepository, times(0)).save(any(RequestLog.class));160 }161}...
Source:ServiceControllerTest.java
1/*2 * Copyright 1999-2018 Alibaba Group Holding Ltd.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package com.alibaba.nacos.naming.controllers;17import com.alibaba.nacos.api.exception.NacosException;18import com.alibaba.nacos.api.naming.CommonParams;19import com.alibaba.nacos.naming.BaseTest;20import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl;21import com.alibaba.nacos.naming.core.SubscribeManager;22import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;23import com.alibaba.nacos.naming.pojo.Subscriber;24import com.fasterxml.jackson.databind.node.ObjectNode;25import org.junit.Assert;26import org.junit.Before;27import org.junit.Test;28import org.junit.runner.RunWith;29import org.mockito.InjectMocks;30import org.mockito.Mock;31import org.mockito.Mockito;32import org.mockito.junit.MockitoJUnitRunner;33import org.springframework.mock.web.MockHttpServletRequest;34import org.springframework.test.util.ReflectionTestUtils;35import java.util.Arrays;36import java.util.Collections;37@RunWith(MockitoJUnitRunner.class)38public class ServiceControllerTest extends BaseTest {39 40 @InjectMocks41 private ServiceController serviceController;42 43 @Mock44 private ServiceOperatorV2Impl serviceOperatorV2;45 46 @Mock47 private UpgradeJudgement upgradeJudgement;48 49 @Mock50 private SubscribeManager subscribeManager;51 52 @Before53 public void before() {54 super.before();55 ReflectionTestUtils.setField(serviceController, "upgradeJudgement", upgradeJudgement);56 Mockito.when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true);57 }58 59 @Test60 public void testList() throws Exception {61 62 Mockito.when(serviceOperatorV2.listService(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()))63 .thenReturn(Collections.singletonList("DEFAULT_GROUP@@providers:com.alibaba.nacos.controller.test:1"));64 65 MockHttpServletRequest servletRequest = new MockHttpServletRequest();66 servletRequest.addParameter("pageNo", "1");67 servletRequest.addParameter("pageSize", "10");68 69 ObjectNode objectNode = serviceController.list(servletRequest);70 Assert.assertEquals(1, objectNode.get("count").asInt());71 }72 73 @Test74 public void testCreate() {75 try {76 Mockito.when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true);77 String res = serviceController.create(TEST_NAMESPACE, TEST_SERVICE_NAME, 0, "", "");78 Assert.assertEquals("ok", res);79 } catch (Exception e) {80 e.printStackTrace();81 Assert.fail(e.getMessage());82 }83 }84 85 @Test86 public void testRemove() {87 try {88 String res = serviceController.remove(TEST_NAMESPACE, TEST_SERVICE_NAME);89 Assert.assertEquals("ok", res);90 } catch (Exception e) {91 e.printStackTrace();92 Assert.fail(e.getMessage());93 }94 }95 96 @Test97 public void testDetail() {98 try {99 ObjectNode result = Mockito.mock(ObjectNode.class);100 Mockito.when(serviceOperatorV2.queryService(Mockito.anyString(), Mockito.anyString())).thenReturn(result);101 102 ObjectNode objectNode = serviceController.detail(TEST_NAMESPACE, TEST_SERVICE_NAME);103 Assert.assertEquals(result, objectNode);104 } catch (NacosException e) {105 e.printStackTrace();106 Assert.fail(e.getMessage());107 }108 }109 110 @Test111 public void testUpdate() {112 MockHttpServletRequest servletRequest = new MockHttpServletRequest();113 servletRequest.addParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME);114 servletRequest.addParameter("protectThreshold", "0.01");115 try {116 String res = serviceController.update(servletRequest);117 Assert.assertEquals("ok", res);118 } catch (Exception e) {119 e.printStackTrace();120 Assert.fail(e.getMessage());121 }122 }123 124 @Test125 public void testSearchService() {126 try {127 Mockito.when(serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean()))128 .thenReturn(Collections.singletonList("result"));129 130 ObjectNode objectNode = serviceController.searchService(TEST_NAMESPACE, "", true);131 Assert.assertEquals(1, objectNode.get("count").asInt());132 } catch (NacosException e) {133 e.printStackTrace();134 Assert.fail(e.getMessage());135 }136 137 try {138 Mockito.when(serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean()))139 .thenReturn(Arrays.asList("re1", "re2"));140 Mockito.when(serviceOperatorV2.listAllNamespace()).thenReturn(Arrays.asList("re1", "re2"));141 142 ObjectNode objectNode = serviceController.searchService(null, "", true);143 Assert.assertEquals(4, objectNode.get("count").asInt());144 } catch (NacosException e) {145 e.printStackTrace();146 Assert.fail(e.getMessage());147 }148 }149 150 @Test151 public void testSubscribers() {152 Mockito.when(subscribeManager.getSubscribers(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean()))153 .thenReturn(Collections.singletonList(Mockito.mock(Subscriber.class)));154 155 MockHttpServletRequest servletRequest = new MockHttpServletRequest();156 servletRequest.addParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME);157 158 ObjectNode objectNode = serviceController.subscribers(servletRequest);159 Assert.assertEquals(1, objectNode.get("count").asInt());160 }161}...
Source:GroupControllerTest.java
...45 @Test46 public void testCreateGroup() {47 Mockito.when(groupService.isUnique(Mockito.<Group>any())).thenReturn(true);48 Mockito.when(groupService.createAndUpdateGroup(Mockito.<Group>any())).thenReturn(group);49 RequestEntity<Group> request = null;50 try {51 request = new RequestEntity<Group>(group, HttpMethod.POST, new URI("/group"));52 } catch (URISyntaxException e) {53 e.printStackTrace();54 }55 ResponseEntity<Group> response = testRestTemplate.exchange(request, Group.class);56 assertEquals(HttpStatus.CREATED, response.getStatusCode());57 Mockito.verify(groupService, Mockito.times(1)).createAndUpdateGroup(Mockito.<Group>any());58 }59 @Test60 public void testUpdateGroup() {61 }62 @Test63 public void testGetOneGroupByString() {64 Mockito.when(groupService.getGroup(Mockito.anyString())).thenReturn(group);65 RequestEntity<String> request = null;66 try {67 request = new RequestEntity<String>(HttpMethod.GET, 68 new URI("/group/get-group?groupName="+group.getGroupName()));69 } catch (URISyntaxException e) {70 e.printStackTrace();71 }72 ResponseEntity<Group> response = testRestTemplate.exchange(request, Group.class);73 assertEquals(HttpStatus.OK, response.getStatusCode());74 Mockito.verify(groupService, Mockito.times(1)).getGroup(Mockito.<String>any());75 }76 @Test77 public void testGetOneGroupInt() {78 List<Group> groups = Arrays.asList(group);79 Mockito.when(groupService.findAllByCourse(Mockito.anyInt())).thenReturn(groups);80 RequestEntity<String> request = null;81 try {82 request = new RequestEntity<String>(HttpMethod.GET, 83 new URI("/group/get-grouplist?course="+group.getCourse()));84 } catch (URISyntaxException e) {85 e.printStackTrace();86 }87 ResponseEntity<List<Group>> response = testRestTemplate88 .exchange(request, new ParameterizedTypeReference<List<Group>>() {});89 assertEquals(HttpStatus.OK, response.getStatusCode());90 Mockito.verify(groupService, Mockito.times(1)).findAllByCourse(Mockito.anyInt());91 }92 @Test93 public void testDeleteGroup() {94 Mockito.doNothing().when(groupService).deleteGroup(Mockito.anyString());95 RequestEntity<String> request = null;96 try {97 request = new RequestEntity<String>(HttpMethod.DELETE, 98 new URI("/group?groupName="+group.getGroupName()));99 } catch (URISyntaxException e) {100 e.printStackTrace();101 }102 ResponseEntity response = testRestTemplate.exchange(request, ResponseEntity.class);103 assertEquals(HttpStatus.OK, response.getStatusCode());104 Mockito.verify(groupService, Mockito.times(1)).deleteGroup(Mockito.<String>any());105 }106}...
request
Using AI Code Generation
1import org.mockito.Mockito;2public class 1 {3 public static void main(String[] args) {4 List mockedList = Mockito.mock(List.class);5 mockedList.add("one");6 mockedList.clear();7 Mockito.verify(mockedList).add("one");8 Mockito.verify(mockedList).clear();9 }10}11Mockito is a Java library that is used for unit testing purposes. It allows the creation of test double objects in automated unit tests for the purpose of test-driven development (TDD)
request
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.Mockito;3import org.mockito.ArgumentCaptor;4import org.mockito.invocation.InvocationOnMock;5import org.mockito.stubbing.Answer;6import org.mockito.verification.VerificationMode;7import org.mockito.verification.VerificationWithTimeout;8import org.mockito.verification.VerificationAfterDelay;9import org.mockito.exceptions.base.MockitoAssertionError;10import org.mockito.exceptions.misusing.CannotVerifyStubOnlyMock;11import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;12import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;13import org.mockito.exceptions.misusing.NotAMockException;14import org.mockito.exceptions.misusing.UnfinishedVerificationException;15import org.mockito.exceptions.misusing.UnfinishedStubbingException;16import org.mockito.exceptions.misusing.UnnecessaryStubbingException;17import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;18import org.mockito.exceptions.verification.ArgumentsAreDifferent;19import org.mockito.exceptions.verification.NeverWantedButInvoked;20import org.mockito.exceptions.verification.NoInteractionsWanted;21import org.mockito.exceptions.verification.TooLittleActualInvocations;22import org.mockito.exceptions.verification.TooManyActualInvocations;23import org.mockito.exceptions.verification.VerificationInOrderFailure;24import org.mockito.exceptions.verification.junit
request
Using AI Code Generation
1import static org.mockito.Mockito.*;2public class MyClassTest {3 public void testAdd() {4 when(tester.add(10.0,20.0)).thenReturn(30.0);5 Assert.assertEquals(tester.add(10.0,20.0),30.0,0);6 }7}8import static org.mockito.Mockito.*;9public class MyClassTest {10 public void testAdd() {11 when(tester.add(10.0,20.0)).thenReturn(30.0);12 Assert.assertEquals(tester.add(10.0,20.0),30.0,0);13 verify(tester).add(10.0,20.0);14 }15}16import static org.mockito.Mockito.*;17public class MyClassTest {18 public void testAdd() {19 when(tester.add(10.0,20.0)).thenReturn(30.0);20 Assert.assertEquals(tester.add(10.0,20.0),30.0,0);21 verify(tester).add(10.0,20.0);22 verify(tester, times(1)).add(10.0,20.0);23 }24}25import static org.mockito.Mockito.*;26public class MyClassTest {27 public void testAdd() {28 when(tester.add(10.0,20.0)).thenReturn(30.0);
request
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4import org.junit.Test;5import static org.junit.Assert.*;6import static org.mockito.Mockito.*;7import java.util.Arrays;8import java.util.List;9import java.util.ArrayList;10public class TestClass {11 public void test() {12 List mockedList = mock(List.class);13 mockedList.add("one");14 mockedList.clear();15 verify(mockedList).add("one");16 verify(mockedList).clear();17 }18}19import org.mockito.Mockito;20import org.mockito.invocation.InvocationOnMock;21import org.mockito.stubbing.Answer;22import org.junit.Test;23import static org.junit.Assert.*;24import static org.mockito.Mockito.*;25import java.util.Arrays;26import java.util.List;27import java.util.ArrayList;28public class TestClass {29 public void test() {30 LinkedList mockedList = mock(LinkedList.class);31 when(mockedList.get(0)).thenReturn("first");32 System.out.println(mockedList.get(0));33 System.out.println(mockedList.get(999));34 }35}36import org.mockito.Mockito;37import org.mockito.invocation.InvocationOnMock;38import org.mockito.stubbing.Answer;39import org.junit.Test;40import static org.junit.Assert.*;41import static org.mockito.Mockito.*;42import java.util.Arrays;43import java.util.List;44import java.util.ArrayList;45public class TestClass {46 public void test() {47 List mockedList = mock(List.class);48 LinkedList mockedList = mock(LinkedList.class);49 when(mockedList.get(anyInt())).thenReturn("element");50 when(mockedList.contains(argThat(isValid
request
Using AI Code Generation
1import static org.mockito.Mockito.*;2import static org.junit.Assert.*;3import static org.junit.Assert.*;4import org.mockito.*;5import org.mockito.invocation.*;6import org.mockito.stubbing.*;7import org.mockito.verification.*;8import org.mockito.internal.verification.*;9import org.mockito.internal.stubbing.*;10import org.mockito.internal.invocation.*;11import org.mockito.internal.matchers.*;12import org.mockito.internal.progress.*;13import org.mockito.exceptions.base.*;14import org.mockito.exceptions.verification.*;15import org.mockito.exceptions.misusing.*;16import org.mockito.exceptions.reporting.*;17import org.mockito.exceptions.parents.*;18import org.mockito.internal.*;19import org.mockito.internal.matchers.*;20import org.mockito.internal.progress.*;21import org.mockito.internal.stubbing.answers.*;22import org.mockito.internal.verification.api.*;23import org.mockito.internal.verification.checkers.*;24import org.mockito.internal.verification.within.*;25import org.mockito.internal.util.reflection.*;26import org.mockito.internal.util.collections.*;27import org.mockito.internal.invocation.finder.*;28import org.mockito.internal.creation.*;29import org.mockito.internal.creation.ins
request
Using AI Code Generation
1import org.mockito.Mockito.*;2import javax.servlet.http.*;3import java.io.*;4import java.util.*;5import org.junit.Test;6import org.junit.runner.RunWith;7import org.mockito.Mock;8import org.mockito.runners.MockitoJUnitRunner;9import static org.mockito.Mockito.*;10@RunWith(MockitoJUnitRunner.class)11public class TestServlet extends HttpServlet{12 HttpServletRequest request;13 HttpServletResponse response;14 PrintWriter writer;15 public void testServlet() throws Exception {16 when(request.getParameter("name")).thenReturn("John");17 when(response.getWriter()).thenReturn(writer);18 new Servlet().doGet(request, response);19 verify(writer).println("Hello John");20 }21}22import java.io.*;23import javax.servlet.*;24import javax.servlet.http.*;25import java.util.*;26public class Servlet extends HttpServlet{27 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{28 response.setContentType("text/html");29 PrintWriter out = response.getWriter();30 String name = request.getParameter("name");31 out.println("Hello "+name);32 }33}34You are not mocking the response.getWriter() method correctly. You should do something like this:35when(response.getWriter()).thenReturn(writer);36when(response.getWriter()).thenReturn(response.getWriter());
request
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4public class Request {5 public static void main(String[] args) {6 final String[] name = {"John"};7 final int[] age = {20};8 Answer answer = new Answer() {9 public Object answer(InvocationOnMock invocation) throws Throwable {10 String methodName = invocation.getMethod().getName();11 if (methodName.equals("getName")) {12 return name[0];13 } else if (methodName.equals("getAge")) {14 return age[0];15 } else if (methodName.equals("setName")) {16 name[0] = invocation.getArguments()[0].toString();17 } else if (methodName.equals("setAge")) {18 age[0] = Integer.parseInt(invocation.getArguments()[0].toString());19 }20 return null;21 }22 };23 Person person = Mockito.mock(Person.class, answer);24 System.out.println(person.getName());25 System.out.println(person.getAge());26 person.setName("Tom");27 person.setAge(30);28 System.out.println(person.getName());29 System.out.println(person.getAge());30 }31}32import org.mockito.Mockito;33import org.mockito.invocation.InvocationOnMock;34import org.mockito.stubbing.Answer;35public class Request {36 public static void main(String[] args) {37 final String[] name = {"John"};38 final int[] age = {20};39 Answer answer = new Answer() {40 public Object answer(InvocationOnMock invocation) throws Throwable {41 String methodName = invocation.getMethod().getName();42 if (methodName.equals("getName")) {43 return name[0];44 } else if (methodName.equals("getAge")) {45 return age[0];46 } else if (methodName.equals("setName")) {47 name[0] = invocation.getArguments()[0].toString();48 } else if (methodName.equals("setAge")) {49 age[0] = Integer.parseInt(invocation.getArguments()[0].toString());50 }51 return null;52 }53 };54 Person person = Mockito.mock(Person.class, answer);55 System.out.println(person.getName());56 System.out.println(person.getAge());57 person.setName("Tom");58 person.setAge(30);59 System.out.println(person.getName());60 System.out.println(person.getAge());61 }62}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!