### Question:
GatewaySecurityService { public Optional<String> login(String username, String password) { GatewayConfigProperties gatewayConfigProperties = gatewayClient.getGatewayConfigProperties(); String uri = String.format("%s: gatewayConfigProperties.getHostname(), authConfigurationProperties.getGatewayLoginEndpoint()); ObjectMapper mapper = new ObjectMapper(); ObjectNode loginRequest = mapper.createObjectNode(); loginRequest.put("username", username); loginRequest.put("password", password); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); try { ResponseEntity<String> response = restTemplate.exchange( uri, HttpMethod.POST, new HttpEntity<>(loginRequest, headers), String.class); return extractToken(response.getHeaders().getFirst(HttpHeaders.SET_COOKIE)); } catch (HttpClientErrorException | ResourceAccessException | HttpServerErrorException e) { responseHandler.handleBadResponse(e, ErrorType.BAD_CREDENTIALS, "Can not access Gateway service. Uri '{}' returned: {}", uri, e.getMessage()); } return Optional.empty(); }  Optional<String> login(String username, String password); QueryResponse query(String token);  }### Answer:
@Test public void doSuccessfulLogin() { String uri = String.format("%s: gatewayConfigProperties.getHostname(), authConfigurationProperties.getGatewayLoginEndpoint()); HttpEntity loginRequest = createLoginRequest(); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add(HttpHeaders.SET_COOKIE, cookie); when(restTemplate.exchange( eq(uri), eq(HttpMethod.POST), eq(loginRequest), eq(String.class))) .thenReturn(new ResponseEntity<>(responseHeaders, HttpStatus.NO_CONTENT)); Optional<String> token = securityService.login(USERNAME, PASSWORD); assertTrue(token.isPresent()); assertEquals(TOKEN, token.get()); }
@Test public void doLoginWithoutCookie() { String uri = String.format("%s: gatewayConfigProperties.getHostname(), authConfigurationProperties.getGatewayLoginEndpoint()); HttpEntity loginRequest = createLoginRequest(); when(restTemplate.exchange( eq(uri), eq(HttpMethod.POST), eq(loginRequest), eq(String.class))) .thenReturn(new ResponseEntity<>(HttpStatus.NO_CONTENT)); Optional<String> token = securityService.login(USERNAME, PASSWORD); assertFalse(token.isPresent()); }
@Test public void doLoginWhenGatewayUnauthorized() { String uri = String.format("%s: gatewayConfigProperties.getHostname(), authConfigurationProperties.getGatewayLoginEndpoint()); HttpEntity loginRequest = createLoginRequest(); when(restTemplate.exchange( eq(uri), eq(HttpMethod.POST), eq(loginRequest), eq(String.class))) .thenThrow(new HttpClientErrorException(HttpStatus.UNAUTHORIZED)); exceptionRule.expect(BadCredentialsException.class); exceptionRule.expectMessage("Username or password are invalid."); securityService.login(USERNAME, PASSWORD); }